JAVA笔记 | ResponseBodyEmitter等异步流式接口快速学习

先简单记录下简单使用跟测试,后续再补充具体,最近有用到,简单来说就是后端(服务端)编写个发射器,实现一次请求,一直向前端客户端发射数据,直到发射器执行完毕,模拟ai一句一句回复的效果

ResponseBodyEmitter

测试代码

java 复制代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import java.util.Date;
import java.util.concurrent.CompletableFuture;

/**
 * @Author: linjinde
 * @CreateTime: 2024-11-04
 */
@RestController
@RequestMapping("/dify")
public class DifyController {

    @GetMapping("/emitter")
    public ResponseBodyEmitter handle() {
        //创建ResponseBodyEmitter发射器,-1代表不超时
        ResponseBodyEmitter emitter = new ResponseBodyEmitter(-1L);
        CompletableFuture.runAsync(() -> {
            try {
                for (int i = 0; i < 10000; i++) {
                    System.out.println("bodyEmitter " + i);
                    //发送数据
                    emitter.send("bodyEmitter " + i + " @ " + new Date() + "\n");
                    //模拟两秒响应一次
                    Thread.sleep(2000);
                }
                emitter.complete();
            }catch (Exception e){
                // 发生异常时结束接口
                emitter.completeWithError(e);
            }

        });
        //postman或者网页无法直接现实响应体,因为发射器是设计面向客户端,要显示设计歌简单js客户端接收
        return emitter;
    }
}

请求测试

因为ResponseBodyEmitter是设计面向客户端持续发送数据,故postman跟网页正常情况下是不支持数据连续现实,需要javascript编写简单客户端才可以显示返回内容,对于后端来说很麻烦。

简单解决方法:这边就用cmd curl直接请求

测试完毕

后续继续补充SseEmitter等

相关推荐
2501_918126911 小时前
stm32做一个次声波检测器,需要哪些元件
stm32·单片机·嵌入式硬件·学习·个人开发
GocNeverGiveUp2 小时前
大模型学习2-Agent
学习
Bal炎魔2 小时前
AI 学习专题一,AI 实现的原理
人工智能·学习
Ro Jace3 小时前
分岔机制学习
人工智能·学习·机器学习
雾岛听蓝4 小时前
C++11新特性(lambda、包装器)
c++·经验分享·笔记
反向跟单策略4 小时前
期货反向跟单-2025年回顾及2026年展望
大数据·人工智能·学习·数据分析·区块链
yunhuibin4 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
xcLeigh5 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
知识分享小能手5 小时前
PostgreSQL 入门学习教程,从入门到精通,PostgreSQL 16 语法知识点与案例详解(1)
数据库·学习·postgresql
代码游侠5 小时前
Linux驱动复习——驱动
linux·运维·arm开发·笔记·学习