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等

相关推荐
UpUpUp……5 小时前
HTML简单语法标签(后续实操:云备份项目)
笔记·html
小彭律师5 小时前
门禁人脸识别系统详细技术文档
笔记·python
是孑然呀6 小时前
【小记】word批量生成准考证
笔记·学习·excel
ll7788119 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
LuckyLay10 小时前
React百日学习计划——Deepseek版
前端·学习·react.js
安和昂10 小时前
【iOS】SDWebImage源码学习
学习·ios
毫秒AI获客10 小时前
小红书多账号运营效率优化:技术方案与自动化实践
笔记
菜一头包10 小时前
c++ std库中的文件操作学习笔记
c++·笔记·学习
猴子请来的逗比48910 小时前
tomcat搭建内网论坛
学习·tomcat
belldeep10 小时前
如何阅读、学习 Git 核心源代码 ?
git·学习·源代码