SpringBoot+SseEmitter 异步推送消息给前端
一次http请求,后端推送多条数据,http长连接private static final Map<Long, SseEmitter> SSE_EMITTER_MAP = new HashMap<>(16);@GetMapping("/{id}")public SseEmitter getSseEmitter(@PathVariable Long id) {//0L设置永不
·
一次http请求,后端推送多条数据,http长连接
private static final Map<Long, SseEmitter> SSE_EMITTER_MAP = new HashMap<>(16);
@GetMapping("/{id}")
public SseEmitter getSseEmitter(@PathVariable Long id) {
//0L设置永不超时
SseEmitter sseEmitter = new SseEmitter(0L);
SSE_EMITTER_MAP.put(id, sseEmitter);
return sseEmitter;
}
//这个方法仅仅是测试,可根据业务来推送
@PostMapping("/{id}")
public void test(@PathVariable Long id) throws IOException, InterruptedException {
//每3s向前端推送消息
SseEmitter emitter = SSE_EMITTER_MAP.get(id);
for (int i = 0; i < 10; i++) {
emitter.send("后端推送信息" + i);
Thread.sleep(3000);
}
emitter.complete();
}
前端代码
<body>
<div id="message"></div>
<script src="../static/jquery-2.1.1.min.js"></script>
<script>
$("button").click(function () {
var source = new EventSource('http://localhost:8080/api/SseEmitter/' + userId);
source.addEventListener('message', function (e) {
console.log(e.data);
document.getElementById("message").innerHTML += e.data + '<br>';
}, false);
source.addEventListener('error', function (e) {
console.log("异常:" + e.data)
});
});
</script>
</body>
简单两步实现后台持续向前端推送信息,如下载的进度条就可以实现了
更多推荐
已为社区贡献1条内容
所有评论(0)