package com.backendsys.modules.sse.controller; import cn.hutool.core.convert.Convert; import com.backendsys.modules.common.config.security.utils.HttpRequestUtil; import com.backendsys.modules.common.config.security.utils.SecurityUtil; import com.backendsys.modules.sse.emitter.SseEmitterManager; import com.backendsys.modules.sse.entity.SseResponse; import com.backendsys.modules.sse.entity.SseResponseEnum; import com.backendsys.modules.sse.utils.SseEmitterUTF8; import com.backendsys.modules.sse.utils.SseUtil; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.io.IOException; @RestController public class SseController { @Value("${spring.application.name}") private String APPLICATION_NAME; @Autowired private SseUtil sseUtil; @Autowired private HttpRequestUtil httpRequestUtil; /** * [SSE] 消息监听 (拼接键值: 应用名称-用户ID) */ @GetMapping(value = "/api/sse/listenStream", produces = "text/event-stream;charset=UTF-8") public SseEmitter stream(HttpServletResponse response) { // 获得 浏览器窗口UUID String browserWindowUUID = httpRequestUtil.getBrowserWindowUUID(); // 拼接键值: 应用名称-用户ID-浏览器窗口UUID String emitterKey = APPLICATION_NAME + "-userid-" + Convert.toStr(SecurityUtil.getUserId() + "-" + browserWindowUUID); // 如果存在,则关闭 sseUtil.closeIfExist(emitterKey); // System.out.println("browserWindowUUID = " + browserWindowUUID); // System.out.println("emitterKey = " + emitterKey); SseEmitterUTF8 emitter = new SseEmitterUTF8(Long.MAX_VALUE); SseEmitterManager manager = SseEmitterManager.getInstance(); manager.addEmitter(emitterKey, emitter); try { // 设置响应头,指定字符编码 response.setCharacterEncoding("UTF-8"); response.setContentType("text/event-stream"); // CONNECT: 建立连接 String dataStr = (new SseResponse(SseResponseEnum.CONNECT)).toJsonStr(); emitter.send(SseEmitter.event().data(dataStr)); } catch (IOException e) { // 关闭连接 System.out.println("(listenStream):" + e.getMessage()); } finally { manager.removeEmitter(emitter); } return emitter; } /** * [SSE] 测试发送 (单个) */ @GetMapping("/api/sse/sendHello") public String sendHelloWorld() { String dataStr = (new SseResponse("Hello World")).toJsonStr(); sseUtil.send(SecurityUtil.getUserId(), dataStr); return "success"; } /** * [SSE] 测试发送 (全部) */ @GetMapping("/api/sse/sendHelloToAll") public String sendHelloWorldToAll() { String dataStr = (new SseResponse("Hello World Everyone")).toJsonStr(); sseUtil.sendToAll(dataStr); return "success"; } }