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等

相关推荐
✎ ﹏梦醒͜ღ҉繁华落℘6 分钟前
FreeRTOS学习笔记(应用)-- 各种 信号量的应用场景
笔记·学习
星星火柴93611 分钟前
笔记 | C++面向对象高级开发
开发语言·c++·笔记·学习
BeingACoder19 分钟前
【SAA】SpringAI Alibaba学习笔记(一):SSE与WS的区别以及如何注入多个AI模型
java·笔记·学习·saa·springai
安全不再安全1 小时前
免杀技巧 - 早鸟注入详细学习笔记
linux·windows·笔记·学习·测试工具·web安全·网络安全
BreezeJuvenile1 小时前
外设模块学习(8)——HC-SR04超声波模块(STM32)
stm32·单片机·嵌入式硬件·学习·超声波测距模块·hc-sr04
LBuffer2 小时前
破解入门学习笔记题三十八
笔记·学习
微露清风2 小时前
系统性学习C++-第十讲-stack 和 quene
java·c++·学习
PyAIGCMaster2 小时前
钉钉的设计理念方面,我可以学习
人工智能·深度学习·学习·钉钉
Elias不吃糖3 小时前
第四天学习总结:C++ 文件系统 × Linux 自动化 × Makefile 工程化
linux·c++·学习
CodeCraft Studio3 小时前
PPT处理控件Aspose.Slides教程:使用Java将PowerPoint笔记导出为PDF
java·笔记·pdf·powerpoint·aspose·ppt转pdf·java将ppt导出pdf