SSE 是一种允许服务器通过 HTTP 协议主动向客户端推送事件的技术。它特别适合那些实时性要求高、但不需要客户端频繁发送数据的场景,比如实时消息通知、进度更新、数据流推送等。
xml<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
javaimport 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.Executors;
import java.util.concurrent.TimeUnit;
@RestController
public class SseController {
@GetMapping("/sse/demo")
public SseEmitter streamSse() {
// 1. 创建 SseEmitter 实例,设置超时时间(毫秒)
SseEmitter emitter = new SseEmitter(60_000L);
// 2. 使用线程池异步执行,避免阻塞主线程
Executors.newSingleThreadExecutor().execute(() -> {
try {
for (int i = 1; i <= 10; i++) {
// 3. 模拟数据发送(例如实时消息)
emitter.send("当前消息:" + i);
TimeUnit.SECONDS.sleep(1);
}
// 4. 发送完成后关闭连接
emitter.complete();
} catch (IOException | InterruptedException e) {
// 异常处理,将错误信息发送给客户端并关闭连接
emitter.completeWithError(e);
}
});
return emitter;
}
}
html<script>
// 连接 SSE 接口
const eventSource = new EventSource('/sse/demo');
// 监听消息
eventSource.onmessage = function(event) {
console.log('收到实时消息:', event.data);
// 根据实际需要更新页面,例如追加到 div 中
// document.getElementById('messages').innerHTML += event.data + '<br/>';
};
// 异常处理
eventSource.onerror = function(err) {
console.error('SSE 连接异常:', err);
// 可在此处尝试重连或提示用户
};
// 需要关闭连接时调用
// eventSource.close();
</script>
本文作者:Weee
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!