springboot使用SSE

1、pom文件

XML 复制代码
 <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

2、前端代码

html 复制代码
<!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、订阅
java 复制代码
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、推送
java 复制代码
@GetMapping(path = "push/{userId}")
	public String push(@PathVariable String userId,@RequestBody Map<String,Object> param) throws IOException {
		try {
			SseEmitter sseEmitter = cache.get("123");
			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、关闭
java 复制代码
@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";
	}
相关推荐
影子24016 分钟前
oralce创建种子表,使用存储过程生成最大值sql,考虑并发,不考虑并发的脚本,plsql调试存储过程,java调用存储过程示例代码
java·数据库·sql
武子康11 分钟前
Java-172 Neo4j 访问方式实战:嵌入式 vs 服务器(含 Java 示例与踩坑)
java·服务器·数据库·sql·spring·nosql·neo4j
程序猿DD16 分钟前
深入探索剖析 JVM 的启动过程
java
白露与泡影22 分钟前
Spring Boot项目优化和JVM调优
jvm·spring boot·后端
ruleslol24 分钟前
SpringBoot18-redis的配置
spring boot·redis
是店小二呀25 分钟前
五分钟理解Rust的核心概念:所有权Rust
开发语言·后端·rust
Arva .35 分钟前
ConcurrentHashMap 的线程安全实现
java·开发语言
听风吟丶1 小时前
Java 9+ 模块化系统(Jigsaw)实战:从 Jar 地狱到模块解耦的架构升级
java·架构·jar
昂子的博客1 小时前
Redis缓存 更新策略 双写一致 缓存穿透 击穿 雪崩 解决方案... 一篇文章带你学透
java·数据库·redis·后端·spring·缓存