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

springboot使用SSE

1、pom文件 

 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>

2、前端代码

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title> Springboot集成SSE </title>
</head>
<script>let source = null;const clientId = new Date().getTime();if (!!window.EventSource) {source = new EventSource('http://127.0.0.1:8080/sse/subscribe?id=' + clientId);//建立连接source.onopen = function (event) {setMessageInnerHTML("建立连接" + event);}//接收数据source.onmessage = function (event) {setMessageInnerHTML(event.data);}//错误监听source.onerror = function (event) {if (event.readyState === EventSource.CLOSED) {setMessageInnerHTML("连接关闭");} else {console.log(event);}}} else {setMessageInnerHTML("浏览器不支持SSE");}window.onbeforeunload = function () {close();};// 关闭function close() {source.close();const httpRequest = new XMLHttpRequest();httpRequest.open('GET', '/sse/over/?clientId=' + clientId, true);httpRequest.send();console.log("close");}// 显示消息function setMessageInnerHTML(innerHTML) {document.getElementById('text').innerHTML += innerHTML + '<br/>';}
</script>
<body>
<button onclick="close()">关闭连接</button>
<div id="text"></div>
</body>
</html>

3、后端代码

1、订阅
private static Map<String, SseEmitter> cache = new ConcurrentHashMap<>();@GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})public SseEmitter subscribe(@RequestParam(name = "id", required = false) String id) throws IOException {// 超时时间设置SseEmitter sseEmitter = new SseEmitter(0L);cache.put(id, sseEmitter);//结束连接sseEmitter.onCompletion(() -> {log.info("结束连接:{}", id);cache.remove(id);});//连接异常sseEmitter.onError(throwable -> {log.info("连接异常:{}", id);cache.remove(id);});//连接超时sseEmitter.onTimeout(() -> {log.info("连接超时:{}", id);cache.remove(id);});return sseEmitter;}
2、推送
@GetMapping(path = "push/{userId}")public String push(@PathVariable String userId,@RequestBody Map<String,Object> param) throws IOException {try {SseEmitter sseEmitter = cache.get(userId);if (sseEmitter != null) {sseEmitter.send(SseEmitter.event().name("msg").data("后端发送消息:" + param));}} catch (IOException e) {log.error("用户[{}]推送异常:{}", userId, e.getMessage());cache.remove(userId);}return "over";}
3、关闭
@GetMapping(path = "over")public String over(@RequestParam(name = "id", required = false) String id) {SseEmitter sseEmitter = cache.get(id);if (sseEmitter != null) {sseEmitter.complete();cache.remove(id);}return "over";}

http://www.lryc.cn/news/174470.html

相关文章:

  • 搞定ESD(一):静电放电测试标准解析
  • 问界M7的诸多优点(自动驾驶走进我们的生活二)
  • [运维|数据库] msql中的 FIND_IN_SET如何转化为pg数据中的ARRAY_POSITION的函数
  • LeetCode 面试题 05.03. 翻转数位
  • Fiddler抓包工具配置+Jmeter基本使用
  • IOTE 2023国际物联网展直击:芯与物发布全新定位芯片,助力多领域智能化发展
  • 【软件设计师-从小白到大牛】上午题基础篇:第二章 操作系统
  • 【20230921】关于sing-box命令行程序开机自启动运行(Windows、Linux)
  • LeetCode 75-02:字符串的最大公因子
  • k8s1.19使用ceph14
  • Leetcode 50. Pow(x, n)
  • hive分区表的元数据信息numRows显示为0
  • Baumer工业相机堡盟工业相机如何通过BGAPI SDK设置相机的图像剪切(ROI)功能(C++)
  • 【云原生】聊聊为什么需要docker以及其基础架构
  • “高级前端开发技术探索路由的使用及Node安装使用“
  • LeetCode 494.目标和 (动态规划 + 性能优化)二维数组 压缩成 一维数组
  • [36c3 2019]includer
  • Python150题day10
  • Autosar工具-Davinci Developer
  • js中的数据结构:栈,队列,链表,字典哈希表,树
  • Verdi实现信号的平移
  • Leetcode算法入门与数组丨6. 数组双指针、滑动窗口
  • 推荐一本书《横向领导力》
  • React实战过程的知识了解
  • F对象和Q对象
  • Visio——绘制倾斜线段
  • Linux复习-安装与熟悉环境(一)
  • Go基础语法:map
  • 开发板TFTP调试
  • MySQL---优化日志