一、什么是SSE
严格地说,HTTP 协议无法做到服务器主动推送信息。但是,有一种变通方法,就是服务器向客户端声明,接下来要发送的是流信息(streaming)。
也就是说,发送的不是一次性的数据包,而是一个数据流,会连续不断地发送过来。这时,客户端不会关闭连接,会一直等着服务器发过来的新的数据流,视频播放就是这样的例子。本质上,这种通信就是以流信息的方式,完成一次用时很长的下载。
SSE 就是利用这种机制,使用流信息向浏览器推送信息。它基于 HTTP 协议,目前除了 IE/Edge,其他浏览器都支持。
二、如何在java中实现SSE
在Spring Boot项目中,无需额外引入特定的依赖,因为Spring Web MVC模块已经内置了对SSE的支持。
1、编写SSE服务,来进行创建链接和发送消息
package com.smart3dmap.prjpntmanage.service; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.io.IOException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Slf4j @Service public class SSEService { private static final Map<String,SseEmitter> sseEmitterMap = new ConcurrentHashMap<>(); public SseEmitter crateSse(String uid) { SseEmitter sseEmitter = new SseEmitter(0L); sseEmitter.onCompletion(() -> { log.info("[{}]结束链接" , uid); sseEmitterMap.remove(uid); }); sseEmitter.onTimeout(() -> { log.info("[{}]链接超时",uid); }); sseEmitter.onError(throwable -> { try{ log.info("[{}]链接异常,{}",uid,throwable.toString()); sseEmitter.send(SseEmitter.event() .id(uid) .name("发生异常") .data("发生异常请重试") .reconnectTime(3000)); sseEmitterMap.put(uid,sseEmitter); }catch (IOException e){ e.printStackTrace(); } }); try{ sseEmitter.send(SseEmitter.event().reconnectTime(5000)); }catch (IOException e){ e.printStackTrace(); } sseEmitterMap.put(uid,sseEmitter); log.info("[{}]创建sse连接成功!",uid); return sseEmitter; } public boolean sendMessage(String uid,String messageId,String message){ if(StringUtils.isEmpty(message)){ log.info("[{}]参数异常,msg为空",uid); return false; } SseEmitter sseEmitter = sseEmitterMap.get(uid); if(sseEmitter == null){ log.info("[{}]sse连接不存在",uid); return false; } try{ sseEmitter.send(SseEmitter.event().id(messageId).reconnectTime(60000).data(message)); log.info("用户{},消息ID:{},推送成功:{}",uid,messageId,message); return true; }catch (IOException e){ sseEmitterMap.remove(uid); log.info("用户{},消息ID:{},消息推送失败:{}",uid,messageId,message); sseEmitter.complete(); return false; } } public void closeSse(String uid){ if(sseEmitterMap.containsKey(uid)){ SseEmitter sseEmitter = sseEmitterMap.get(uid); sseEmitter.complete(); sseEmitterMap.remove(uid); }else { log.info("用户{}连接已关闭",uid); } } }
2、编写对应的Controller来实现具体业务
package com.test.controller; import cn.hutool.core.util.IdUtil; import com.test.service.SSEService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; @Controller @RequestMapping("test") public class TestController { @Autowired private SSEService sseService; @GetMapping("createSse") @CrossOrigin public SseEmitter createSse(String uid) { return sseService.crateSse(uid); } @GetMapping("sendMsg") @ResponseBody @CrossOrigin public String sseChat(String uid){ for (int i = 0; i < 10; i++) { sseService.sendMessage(uid,"消息"+i,IdUtil.fastUUID().replace("-","")); } return "OK"; } @GetMapping("closeSse") @CrossOrigin public void closeSse(String uid){ sseService.closeSse(uid); } }
三、前端实现消息的监听
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>SSE消息推送监听</title> </head> <body> <div id="conMsg"></div> <script> let uid = 1; let chat = document.getElementById("conMsg"); if(window.EventSource){ var eventSource = new EventSource(`http://127.0.0.1:8090/test/createSse?uid=${uid}`); eventSource.onopen = ()=>{ console.log("链接成功"); } eventSource.onmessage = (ev)=>{ if(ev.data){ chat.innerHTML += ev.data+"<br>"; } } eventSource.onerror = ()=>{ console.log("sse链接失败") } }else{ alert("当前浏览器不支持sse") } </script> </body> </html>