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

spring boot 使用SSE向前端推送数据

SSE(Server-Sent Events)是一种基于HTTP的实时通信协议,它允许服务器向客户端发送持久性的数据流。与WebSocket不同的是,SSE是单向通信,只能由服务器向客户端发送数据。Spring Boot通过Spring WebFlux模块提供了对SSE的支持。下面是一个简单的示例:
1、后端

package com.example.springbootmp.controller;import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import java.io.IOException;
import java.util.Map;
import java.util.concurrent.*;@Controller
@RequestMapping(path = "sse")
@CrossOrigin("*")
public class SseRest {private final static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();/*** 连接sse服务,并向前端推送数据* @param id* @return* @throws IOException*/@GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})@SneakyThrowspublic SseEmitter push(String id) throws IOException {// 超时时间设置为5分钟,用于演示客户端自动重连SseEmitter sseEmitter = new SseEmitter(5_60_000L);// 设置前端的重试时间为1ssseCache.put(id, sseEmitter);ExecutorService executorService= Executors.newFixedThreadPool(1,(Runnable r)->{Thread t=new Thread(r);t.setDaemon(true);return t;});SseEmitter.SseEventBuilder data = SseEmitter.event().name("message").id(id).data("测试数据");executorService.execute(()->{while (true){if(sseCache.containsKey(id)){System.out.println("发送");try {sseEmitter.send(data);Thread.sleep(2000);} catch (IOException e) {e.printStackTrace();}catch (InterruptedException e) {e.printStackTrace();}}else {System.out.println("结束");break;}}});//        while (true){
//            sseEmitter.send("测试数据",MediaType.APPLICATION_JSON);
//            Thread.sleep(1000);
//        }// onCompletion(): 结束之后的回调触发//sseEmitter.onCompletion(() -> System.out.println("完成!!!"));return sseEmitter;}/*** http://127.0.0.1:8080/sse/push?id=7777&content=%E4%BD%A0%E5%93%88aaaaaa* @param id* @param content* @return* @throws IOException*/@ResponseBody@GetMapping(path = "push")public String push(String id, String content) throws IOException {SseEmitter sseEmitter = sseCache.get(id);if (sseEmitter != null) {sseEmitter.send(content);}return "over";}@ResponseBody@GetMapping(path = "/over/{id}")public String over(@PathVariable("id") String id) {SseEmitter sseEmitter = sseCache.get(id);if (sseEmitter != null) {// complete(): 表示执行完毕,会断开连接sseEmitter.complete();sseCache.remove(id);}return "over";}
}

2、前端

var source
//开始建立连接部分
source = new EventSource('http://localhost:9999/sse/subscribe?id=122')source.addEventListener('message',function(event) {console.log('接收数据')console.log(event.data)},false)
//关闭连接部分
source.close()
http://www.lryc.cn/news/192596.html

相关文章:

  • C++智能指针(三)——unique_ptr初探
  • Composition Api 与 Options Api 有什么区别?
  • 紫光同创FPGA实现UDP协议栈网络视频传输,基于YT8511和RTL8211,提供4套PDS工程源码和技术支持
  • 深度学习简述
  • 【从零开始学习Redis | 第二篇】Redis中的数据类型和相关命令
  • 数据结构 - 3(链表12000字详解)
  • Jmeter性能测试插件jpgc的安装
  • 关于safari浏览器浏览html video标签无法正常播放的问题
  • 【C++代码】最大二叉树,合并二叉树,二叉搜索树中的搜索,验证二叉搜索树--代码随想录
  • 母婴用品会员商城小程序的作用是什么
  • c++初阶--内存管理
  • Burstormer论文阅读笔记
  • Apifox 学习笔记 - 前置操作之:动态更新请求体中的时间戳
  • 2023年9月 青少年软件编程等级考试Scratch二级真题
  • 12.验证码以及付费代理
  • 使用Plotly可视化
  • 【C语言】结构体、位段、枚举、联合(共用体)
  • “Python+”集成技术高光谱遥感数据处理与机器学习深度应用
  • Excel 转为 PDF,PNG,HTML等文件
  • docker中使用GPU+rocksdb
  • 好用的跨平台同步笔记工具,手机和电脑可同步的笔记工具
  • 【Python 千题 —— 基础篇】浮点数转换为整数
  • 金融科技论文D部分
  • Apache Tomcat下载安装配置使用超详细
  • 基于Seata的分布式事务方案
  • 指令跳转:原来if...else就是goto
  • 【数据库系统概论】第四章数据库安全性
  • 如何正确的关闭Redis服务器
  • MySQL日志管理和权限管理(重点)
  • Maven 使用教程(二)