SseEmitter 伺服器向客戶端推送訊息

黑狗已醒發表於2024-12-02

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 java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class SseController {

private final ExecutorService nonBlockingService = Executors.newCachedThreadPool();

@GetMapping("/sse")
public SseEmitter handleSse() {
SseEmitter emitter = new SseEmitter();

nonBlockingService.execute(() -> {
try {
for (int i = 0; i < 10; i++) {
SseEmitter.SseEventBuilder event = SseEmitter.event()
.data("SSE event - " + i)
.id(String.valueOf(i))
.name("sse event")
.reconnectTime(10_000L);
emitter.send(event);
Thread.sleep(1000); // 模擬延遲
}
emitter.complete(); // 完成傳送
} catch (IOException | InterruptedException e) {
emitter.completeWithError(e);
}
});

return emitter;
}
}

相關文章