lifang пре 3 месеци
родитељ
комит
5714f1976e

+ 24 - 6
tr-modules/tr-module-smartFollowUp/src/main/java/cn/tr/module/smart/app/controller/SseController.java

@@ -4,23 +4,41 @@ import cn.dev33.satoken.annotation.SaIgnore;
 import org.springframework.http.MediaType;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
 import javax.annotation.PostConstruct;
+import java.io.IOException;
 import java.time.LocalTime;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 import java.util.stream.Stream;
 
 @RestController
 @SaIgnore
 public class SseController {
-
+    private final ExecutorService executorService = Executors.newFixedThreadPool(10);
     @PostConstruct
     public void init(){
         System.out.println("123");
     }
-    @GetMapping(value = "/sse/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
-    public Stream<String> stream() {
-        // 模拟数据流
-        return Stream.generate(() -> "当前时间:" + LocalTime.now())
-                     .limit(10); // 限制10条消息
+    @GetMapping(value = "/sse/stream",  produces = MediaType.TEXT_EVENT_STREAM_VALUE + ";charset=UTF-8")
+    public SseEmitter stream() {
+        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
+
+        executorService.execute(() -> {
+            try {
+                for (int i = 0; i < 10; i++) {
+                    emitter.send(SseEmitter.event()
+                            .name("message")
+                            .data("当前时间:" + LocalTime.now()));
+                    Thread.sleep(1000); // 每秒发送一次
+                }
+                emitter.complete();
+            } catch (IOException | InterruptedException e) {
+                emitter.completeWithError(e);
+            }
+        });
+
+        return emitter;
     }
 }