|
@@ -1,17 +1,19 @@
|
|
|
package com.backendsys.modules.sse.controller;
|
|
|
|
|
|
import cn.hutool.core.convert.Convert;
|
|
|
+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.web.bind.annotation.GetMapping;
|
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
|
|
|
|
|
import java.io.IOException;
|
|
|
-import java.util.concurrent.ExecutorService;
|
|
|
-import java.util.concurrent.Executors;
|
|
|
|
|
|
@RestController
|
|
|
public class SseController {
|
|
@@ -23,21 +25,28 @@ public class SseController {
|
|
|
* [SSE] 消息监听
|
|
|
*/
|
|
|
@GetMapping(value = "/api/sse/stream", produces = "text/event-stream;charset=UTF-8")
|
|
|
- public SseEmitter stream() {
|
|
|
- String userId = Convert.toStr(1L);
|
|
|
+ public SseEmitter stream(HttpServletResponse response) {
|
|
|
+ // 获得当前用户Id
|
|
|
+ String userId = Convert.toStr(SecurityUtil.getUserId());
|
|
|
+
|
|
|
+ // 如果存在,则关闭
|
|
|
+ sseUtil.closeIfExist(userId);
|
|
|
+
|
|
|
SseEmitterUTF8 emitter = new SseEmitterUTF8(Long.MAX_VALUE);
|
|
|
SseEmitterManager manager = SseEmitterManager.getInstance();
|
|
|
manager.addEmitter(userId, emitter);
|
|
|
try {
|
|
|
- // 如果存在,则关闭
|
|
|
- sseUtil.closeIfExist(userId);
|
|
|
- // 创建新连接
|
|
|
- manager.addEmitter(userId, emitter);
|
|
|
- emitter.send(SseEmitter.event().data("Connected successfully! (连接成功)"));
|
|
|
+ // 设置响应头,指定字符编码
|
|
|
+ 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) {
|
|
|
// 关闭连接
|
|
|
- // emitter.complete();
|
|
|
- manager.emitters.remove(emitter);
|
|
|
+ System.out.println("(/api/sse/stream)(controller):" + e.getMessage());
|
|
|
+ manager.removeEmitter(emitter);
|
|
|
}
|
|
|
return emitter;
|
|
|
}
|
|
@@ -47,8 +56,8 @@ public class SseController {
|
|
|
*/
|
|
|
@GetMapping("/api/sse/send")
|
|
|
public String send() {
|
|
|
- String message = "{\"message\": \"Hello World\"}";
|
|
|
- sseUtil.send(1L, message);
|
|
|
+ String dataStr = (new SseResponse("Hello World")).toJsonStr();
|
|
|
+ sseUtil.send(SecurityUtil.getUserId(), dataStr);
|
|
|
return "success";
|
|
|
}
|
|
|
|