在Spring Web开发中,SSE(Server Sent Events)是服务端向客户端单向推送数据的轻量方案,常用于实时通知、状态更新等场景。由于SSE基于HTTP长连接实现,若长时间无数据传输,连接可能会被代理或服务器主动断开,因此需要在连接中定期发送心跳(ping)事件来维持连接活性。

SSE心跳事件的作用
SSE协议本身支持ping类型的事件,服务端发送的心跳事件不会携带业务数据,仅用于告知客户端连接仍处于正常状态。客户端收到心跳事件后,会重置连接的超时计时器,避免连接被误断开。在Spring Web中,我们可以通过多种方式实现SSE心跳的发送。
基于SseEmitter实现心跳发送
SseEmitter是Spring Web提供的用于SSE推送的工具类,我们可以通过定时任务定期调用其send方法发送心跳事件。以下是基础实现示例:
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.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@RestController
public class SsePingController {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
@GetMapping(value = "/sse/ping", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter sseWithPing() {
SseEmitter emitter = new SseEmitter(0L); // 设置超时时间为0表示不自动超时
// 启动定时任务,每5秒发送一次心跳
scheduler.scheduleAtFixedRate(() -> {
try {
// 发送ping事件,事件类型为ping,数据为空字符串
emitter.send(SseEmitter.event()
.type("ping")
.data("")
.reconnectTime(5000));
} catch (IOException e) {
emitter.completeWithError(e);
}
}, 0, 5, TimeUnit.SECONDS);
// 监听连接完成事件,关闭定时任务
emitter.onCompletion(() -> scheduler.shutdownNow());
emitter.onError((e) -> scheduler.shutdownNow());
return emitter;
}
}
上述代码中,我们创建了一个超时不限制的SseEmitter实例,然后通过定时任务每5秒发送一次类型为ping的事件,当连接断开时,会自动关闭定时任务避免资源浪费。
基于ResponseBodyEmitter实现心跳发送
如果需要更底层的控制,也可以使用ResponseBodyEmitter实现SSE心跳,不过需要手动拼接SSE协议的格式。示例如下:
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.ResponseBodyEmitter;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@RestController
public class SsePingController2 {
private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
@GetMapping(value = "/sse/ping2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseBodyEmitter sseWithPing2() {
ResponseBodyEmitter emitter = new ResponseBodyEmitter(0L);
scheduler.scheduleAtFixedRate(() -> {
try {
// 手动拼接SSE ping事件格式,event: ping后换行,data: 后换行,再空一行
String pingEvent = "event: pingn" +
"data: n" +
"n";
emitter.send(pingEvent);
} catch (IOException e) {
emitter.completeWithError(e);
}
}, 0, 5, TimeUnit.SECONDS);
emitter.onCompletion(() -> scheduler.shutdownNow());
emitter.onError((e) -> scheduler.shutdownNow());
return emitter;
}
}
客户端接收心跳的处理
前端使用EventSource接收SSE消息时,默认会自动处理ping事件,不需要额外编写处理逻辑,但如果需要自定义处理,可以监听ping事件:
const eventSource = new EventSource('/sse/ping');
// 监听ping事件
eventSource.addEventListener('ping', (event) => {
console.log('收到SSE心跳事件,连接正常');
});
// 监听默认消息事件
eventSource.onmessage = (event) => {
console.log('收到业务消息:', event.data);
};
// 监听错误事件
eventSource.onerror = (error) => {
console.log('SSE连接错误:', error);
};
注意事项
- 心跳间隔需要根据实际业务场景设置,通常建议设置在3-10秒之间,避免间隔过短增加服务端压力,或间隔过长导致连接被断开。
- 当SSE连接断开时,一定要及时关闭对应的定时任务,避免无效的任务继续执行浪费系统资源。
- 如果使用了反向代理(如Nginx),需要配置代理的超时时间,确保代理不会在心跳间隔内主动断开连接,例如Nginx可以配置proxy_read_timeout为60秒以上。
- 发送心跳事件时,数据内容可以为空,也可以携带当前时间戳等简单信息,方便客户端做连接状态校验。
Spring_WebSSE心跳事件ping事件Server_Sent_Events修改时间:2026-06-25 17:15:31