当前位置: 首页 > article >正文

使用 SseEmitter 实现 Spring Boot 后端的流式传输和前端的数据接收

1.普通文本消息的发送和接收

@GetMapping("/stream")public SseEmitter streamResponse() {SseEmitter emitter = new SseEmitter(0L); // 0L 表示永不超时Executors.newSingleThreadExecutor().execute(() -> {try {for (int i = 1; i <= 5; i++) {emitter.send("消息 " + i);Thread.sleep(1000); // 模拟延迟}emitter.complete();} catch (Exception e) {emitter.completeWithError(e);}});return emitter;}
async function fetchStreamData() {const response = await fetch("/api/chat/stream");// 确保服务器支持流式数据if (!response.ok) {throw new Error(`HTTP 错误!状态码: ${response.status}`);}const reader = response.body.getReader();const decoder = new TextDecoder("utf-8");// 读取流式数据while (true) {const { done, value } = await reader.read();if (done) break;// 解码并输出数据const text = decoder.decode(value, { stream: true });console.log("收到数据:", text);}console.log("流式传输完成");
}
// 调用流式请求
fetchStreamData().catch(console.error);

2.使用流式消息发送多个文件流,实现多个文件的传输

//这里相当于每个drawCatalogue对象会创建一个文件流,然后发送过去,list中有几个对象就会发送几个文件
//之所以要每个属性都手动write一下,是因为我的每个ajaxResult数据量都特别大,容易内存溢出。如果没有我这种特殊情况的话,直接使用JSONObject.toJSONString(drawCatalogue)就可以,不需要去手动写入每个属性。
public SseEmitter getAllDrawDataThree(String cadCode) {SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE); // 设置超时时间为最大值,防止自动结束try {Long code = Long.parseLong(cadCode);DrawExcelList drawExcelList = new DrawExcelList();drawExcelList.setCadCode(code);List<DrawCatalogue> drawCatalogueList = drawExcelListService.treeTableCatalogue(drawExcelList);int splitSize = 20;List<DrawCatalogue> newDrawCatalogueList = splitDrawCatalogueList(drawCatalogueList, splitSize);for (int i = 0; i < newDrawCatalogueList.size(); i++) {String filePath = "drawCatalogue" + i + ".json"; // 文件路径DrawCatalogue drawCatalogue = newDrawCatalogueList.get(i);try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {writer.write("["); // 开始写入最外层JSON数组writer.write("{");writer.write("\"id\": \"" + drawCatalogue.getId() + "\",");writer.write("\"drawName\": \"" + drawCatalogue.getDrawName() + "\",");writer.write("\"drawType\": \"" + drawCatalogue.getDrawType() + "\",");writer.write("\"combineOutType\": \"" + drawCatalogue.getCombineOutType() + "\",");writer.write("\"num\": \"" + drawCatalogue.getNum() + "\",");writer.write("\"children\": ");writer.write("["); // 开始写入childrenJSON数组boolean first = true; // 用于判断是否是第一个元素List<DrawCatalogue> children = drawCatalogue.getChildren();for (DrawCatalogue child : children) {DrawingMain drawingMain = new DrawingMain();drawingMain.setCadCode(code);drawingMain.setDrawName(child.getCombineOutType());drawingMain.setDrawType(child.getDrawType());AjaxResult ajaxResult = drawingMainService.imgListShow(drawingMain);if (!first) {writer.write(","); // 如果不是第一个元素,写入逗号分隔}String tabletJson = JSONObject.toJSONString(ajaxResult);// 逐个属性写入文件流writer.write("{");writer.write("\"id\": \"" + child.getId() + "\",");writer.write("\"drawName\": \"" + child.getDrawName() + "\",");writer.write("\"combineOutType\": \"" + child.getCombineOutType() + "\",");writer.write("\"drawType\": \"" + child.getDrawType() + "\",");writer.write("\"tabletJson\": " + tabletJson);writer.write("}");first = false; // 标记已经写入了一个元素}writer.write("]"); // 结束children数组writer.write("}");writer.write("]"); // 结束最外层JSON数组} catch (IOException e) {sseEmitter.completeWithError(e);}// 读取并发送文件流//byte[] fileData = Files.readAllBytes(Paths.get(filePath));// 分块读取文件并发送(防止一次性读取的文件过大导致内存溢出)Path path = Paths.get(filePath);ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] buffer = new byte[8192]; // 8KB buffertry (InputStream in = Files.newInputStream(path)) {int bytesRead;while ((bytesRead = in.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}byte[] fileData = outputStream.toByteArray();sseEmitter.send(fileData, MediaType.APPLICATION_OCTET_STREAM);}sseEmitter.complete();} catch (Exception e) {sseEmitter.completeWithError(e);} finally {sseEmitter.complete();}return sseEmitter;}

前端代码,在方法中调用,后端返回几个文件就会弹出几个下载窗口

				const eventSource = new EventSource('http://127.0.0.1:1801/tablet/getAllDrawDataThree');eventSource.onmessage = function(event) {try {const fileData = event.data;const blob = new Blob([fileData], { type: 'application/octet-stream' });const url = window.URL.createObjectURL(blob);const a = document.createElement('a');a.style.display = 'none';a.href = url;a.download = 'file.json'; // 设置下载文件名document.body.appendChild(a);a.click();window.URL.revokeObjectURL(url);document.body.removeChild(a);} catch (error) {console.error('Error processing event data:', error);}};eventSource.onerror = function(event) {console.error('SSE error:', event);};
http://www.lryc.cn/news/2400781.html

相关文章:

  • .net Avalonia 在centos部署
  • MyBatis深度解析:XML/注解配置与动态SQL编写实战
  • 面试经验 对常用 LLM 工具链(如 LlamaFactory)的熟悉程度和实践经验
  • 【conda配置深度学习环境】
  • 力扣4.寻找两个正序数组的中位数
  • 【相机基础知识与物体检测】更新中
  • 【前端】性能优化和分类
  • PPO和GRPO算法
  • ceph 对象存储用户限额满导致无法上传文件
  • rk3588 上运行smolvlm-realtime-webcam,将视频转为文字描述
  • 某航参数逆向及设备指纹分析
  • SQL思路解析:窗口滑动的应用
  • Rust 学习笔记:Box<T>
  • C# 从 ConcurrentDictionary 中取出并移除第一个元素
  • 操作系统学习(十三)——Linux
  • NLP学习路线图(二十二): 循环神经网络(RNN)
  • 每日一C(1)C语言的内存分布
  • Photoshop使用钢笔绘制图形
  • 应用层协议:HTTP
  • 复习——C++
  • SPI通信协议(软件SPI读取W25Q64)
  • PostgreSQL-基于PgSQL17和11版本导出所有的超表建表语句
  • JavaWeb:前后端分离开发-部门管理
  • ArcGIS计算多个栅格数据的平均栅格
  • 字节开源FlowGram:AI时代可视化工作流新利器
  • 如何选择合适的分库分表策略
  • (LeetCode 每日一题)3403. 从盒子中找出字典序最大的字符串 I (贪心+枚举)
  • GPIO的内部结构与功能解析
  • Python训练打卡Day42
  • 深度学习中的负采样