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等

相关推荐
一隅论数智43 分钟前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20161 小时前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
爱吃苹果的日记本2 小时前
离散数学第六课
学习·离散数学
AI职业加油站3 小时前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
深圳老胡3 小时前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
旖旎夜光3 小时前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊3 小时前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
Because_of_Her14 小时前
并查集-听课笔记
笔记·算法·并查集
霍霍的袁4 小时前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio