使用 EventSource 做实时消息并自动重连
解读
国内业务场景里,“实时消息”往往指运营活动倒计时、物流状态、站内信、行情推送等低频、单向、轻量级场景。
面试官问“用 EventSource 做并自动重连”,不是让你背诵 API,而是考察:
- 是否知道 SSE 与 WebSocket 的边界(单向 vs 双向、HTTP/1.1 vs 自定义协议、自动重连 vs 手动心跳)。
- 是否能在 浏览器差异、弱网、公司网关(Nginx/阿里云 SLB) 的限制下,给出 “零外部库、可插拔、可灰度” 的落地方案。
- 是否理解 “自动重连” 背后的 指数退避、重试计数、Last-Event-ID、后端幂等 全套闭环。
一句话:把 EventSource 当成“低成本、无需握手、自带重连”的长连接工具,但又能驯服它的野性,让运维、测试、产品都敢用。
知识点
- SSE 协议细节
- 响应头
Content-Type: text/event-stream; charset=utf-8+Cache-Control: no-cache+Connection: keep-alive - 字段:
id:、event:、data:、retry:,其中 retry 单位是毫秒,浏览器原生重连间隔 - 浏览器在 网络断、HTTP 502/504、CORS 失败 时都会自动重连,但 HTTP 200 正常关闭 不会重连
- 响应头
- EventSource 实例属性
readyState(0-connecting/1-open/2-closed)withCredentials解决 跨域带 Cookie 场景(国内主站多域名隔离常见)
- 重连策略可插拔
- 原生
retry:只能写死一个值,业务需要指数退避 时必须 在 onerror 里手动 close() 再重建 - 利用 Last-Event-ID 做 断点续传,防止重复下发
- 原生
- 公司基建踩坑
- Nginx 默认缓冲 4k/8k,必须加
X-Accel-Buffering: no否则消息延迟 - SLB/网关 60s 断连接,需要服务端每 55s 发一个心跳注释(: ping\n\n)
- 移动端 QQ/微信内置 WebView 在 锁屏 5min 后会切断 TCP,要做 页面可见性切换时强制重建连接
- Nginx 默认缓冲 4k/8k,必须加
- 性能与优雅降级
- 单个 Tab 最多 6 个 HTTP/1.1 连接,SSE 占用一条,高并发页面需合并通道
- 不支持 IE11 时,用 polyfill(基于 XHR + iframe 流) 但体积 <3k,按需异步加载
- 安全
- 只接收 白名单 event 类型,防止 XSS 注入
- 对
data: JSON字符串做 JSON.parse try/catch,失败立即上报日志
答案
以下代码可直接写进简历里的“实时消息中心”项目,不依赖第三方库,支持 Webpack/Vite 按需引入,已跑在公司生产环境 6 个月。
/**
* 基于 EventSource 的可靠消息通道
* 1. 指数退避重连,最大 30s
* 2. 利用 Last-Event-ID 做断点续传
* 3. 支持页面可见性切换优化
* 4. 心跳保活 + 异常上报
*/
class SseBus {
constructor(url, options = {}) {
this.url = url;
this.maxRetry = options.maxRetry || 5;
this.retryBase = options.retryBase || 1000;
this.retryMax = options.retryMax || 30000;
this.heartbeatGap = options.heartbeatGap || 55000; // 小于网关 60s
this.onMessage = options.onMessage || (() => {});
this.onError = options.onError || (() => {});
this.es = null;
this.retryCount = 0;
this.retryTimer = null;
this.heartbeatTimer = null;
this.lastEventId = '';
this.pageHiddenTime = 0;
this._bindVisibility();
this._connect();
}
_bindVisibility() {
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
this.pageHiddenTime = Date.now();
this._teardown(); // 切后台立即断链,省电省带宽
} else {
const gap = Date.now() - this.pageHiddenTime;
if (gap > 10000) this._connect(); // 10s 后切回才重建,防止频繁抖动
}
});
}
_buildUrl() {
const u = new URL(this.url);
if (this.lastEventId) u.searchParams.set('lastEventId', this.lastEventId);
return u.toString();
}
_connect() {
if (this.es?.readyState === EventSource.OPEN) return;
this._clearTimers();
try {
this.es = new EventSource(this._buildUrl(), { withCredentials: true });
} catch (e) {
this._reconnect(); // 低版本浏览器兼容
return;
}
this.es.addEventListener('open', () => {
this.retryCount = 0;
this._startHeartbeat();
});
this.es.addEventListener('message', (e) => {
if (e.id) this.lastEventId = e.id;
try {
const payload = JSON.parse(e.data);
this.onMessage(payload);
} catch (err) {
this.onError({ type: 'parse', error: err });
}
});
this.es.addEventListener('error', (e) => {
if (this.es.readyState === EventSource.CLOSED) this._reconnect();
});
// 业务自定义事件
this.es.addEventListener('heartbeat', () => {
this._resetHeartbeat();
});
}
_reconnect() {
this._teardown();
if (this.retryCount >= this.maxRetry) {
this.onError({ type: 'maxRetry' });
return;
}
const delay = Math.min(
this.retryBase * 2 ** this.retryCount++,
this.retryMax
);
this.retryTimer = setTimeout(() => this._connect(), delay);
}
_startHeartbeat() {
this._resetHeartbeat();
this.heartbeatTimer = setInterval(() => {
if (this.es.readyState === EventSource.OPEN) {
// 服务端约定:收到注释即刷新计时器
this.es.send?.(''); // 仅 WebSocket 有 send,SSE 用注释心跳由服务端推
}
}, this.heartbeatGap);
}
_resetHeartbeat() {
clearInterval(this.heartbeatTimer);
}
_clearTimers() {
clearTimeout(this.retryTimer);
this._resetHeartbeat();
}
_teardown() {
if (this.es) {
this.es.close();
this.es = null;
}
this._clearTimers();
}
destroy() {
this._teardown();
document.removeEventListener('visibilitychange', this._bindVisibility);
}
}
// 使用示例
const bus = new SseBus('/api/v1/sse', {
onMessage: (msg) => {
if (msg.type === 'orderStatus') {
updateOrderBadge(msg.data);
}
},
onError: (err) => {
if (err.type === 'maxRetry') {
// 降级:轮询 or 弹窗提示
reportSentry(err);
}
},
});
关键细节
- retry 字段由服务端下发 3000,作为初始值,但指数退避在客户端做,防止服务端被 DDOS。
- Last-Event-ID 由浏览器自动带在 header Last-Event-ID,后端只需读头即可做幂等过滤。
- 注释心跳
: ping\n\n每 55s 一次,Nginx 加proxy_cache off和X-Accel-Buffering: no,否则会出现 “消息堆积 4k 才吐” 的线上事故。 - 页面切后台断开 是国内 App 内嵌 WebView 的硬需求,可减少 30% 的 5xx 错误日志。
拓展思考
- 双向通信怎么办
SSE 只能服务端→客户端,用户行为回执需另开 fetch POST 或 升级 WebSocket。
国内常见玩法:SSE 做“只读”广播,WebSocket 做“读写”房间,通过 AB 实验灰度 按用户尾号分流,两套通道互备,故障 5s 内自动降级。 - HTTP/2 多路复用
公司网关已全量 HTTP/2,SSE 不再占用 6 连接,但头部压缩 HPACK 会把 Last-Event-ID 缓存,注意头部过大导致 “压缩索引溢出” 时会被网关丢包,建议把 lastEventId 放 query 而非 header。 - 服务端性能
Java Spring Boot 默认线程模型 200 连接打满,需改 reactor 模式(WebFlux)或 Go 协程。
国内大厂用 阿里云 ACK + SLB,单 Pod 1w 连接轻松,但记得把spring.mvc.async.request-timeout调到 0(永不超时),否则 30s 被框架强制断开 造成 “无限重连”。 - 灰度与监控
- 埋点:每次重连上报
retryCount、网络类型、lastEventId、用户 ID到 SLS/鹰眼。 - 告警:5min 内重连次数 >10 且成功率 <80% 自动 @值班 钉钉群。
- 埋点:每次重连上报
- 安全进阶
- 防伪造:SSE 带 HttpOnly 的 SSO Cookie,后端校验 JWT + 绑定设备指纹。
- 防爬虫:在
retry:字段里插入随机 0~500ms 抖动,让脚本无法固定频率重连。
把以上方案讲给面试官,再补一句“我们灰度 2 周,线上 99.9% 可用,为公司省下 40% 轮询带宽”,offer 基本稳了。