我看到我的问题得到了一些关注,所以我决定发布我的解决方案。回答我的问题:“这真的是最好的做法,省略重新连接功能吗? ”我不知道:)。但是这个解决方案对我有用,并且在生产中得到了证明,它提供了在某种程度上实际控制 SSE 重新连接的方法。
这是我所做的:
- 重写
createSseSource函数,返回类型为void
- 来自 SSE 的数据不是返回 observable,而是馈送到主题/NgRx 操作
- 添加了公共
openSseChannel和私有reconnectOnError功能以更好地控制
processSseEvent添加了处理自定义消息类型的私有函数
由于我在这个项目上使用 NgRx,每条 SSE 消息都会发送相应的操作,但这可以替换ReplaySubject为observable.
// Public function, initializes connection, returns true if successful
openSseChannel(): boolean {
this.createSseEventSource();
return !!this.eventSource;
}
// Creates SSE event source, handles SSE events
protected createSseEventSource(): void {
// Close event source if current instance of SSE service has some
if (this.eventSource) {
this.closeSseConnection();
this.eventSource = null;
}
// Open new channel, create new EventSource
this.eventSource = new EventSource(this.sseChannelUrl);
// Process default event
this.eventSource.onmessage = (event: MessageEvent) => {
this.zone.run(() => this.processSseEvent(event));
};
// Add custom events
Object.keys(SSE_EVENTS).forEach(key => {
this.eventSource.addEventListener(SSE_EVENTS[key], event => {
this.zone.run(() => this.processSseEvent(event));
});
});
// Process connection opened
this.eventSource.onopen = () => {
this.reconnectFrequencySec = 1;
};
// Process error
this.eventSource.onerror = (error: any) => {
this.reconnectOnError();
};
}
// Processes custom event types
private processSseEvent(sseEvent: MessageEvent): void {
const parsed = sseEvent.data ? JSON.parse(sseEvent.data) : {};
switch (sseEvent.type) {
case SSE_EVENTS.STATUS: {
this.store.dispatch(StatusActions.setStatus({ status: parsed }));
// or
// this.someReplaySubject.next(parsed);
break;
}
// Add others if neccessary
default: {
console.error('Unknown event:', sseEvent.type);
break;
}
}
}
// Handles reconnect attempts when the connection fails for some reason.
// const SSE_RECONNECT_UPPER_LIMIT = 64;
private reconnectOnError(): void {
const self = this;
this.closeSseConnection();
clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = setTimeout(() => {
self.openSseChannel();
self.reconnectFrequencySec *= 2;
if (self.reconnectFrequencySec >= SSE_RECONNECT_UPPER_LIMIT) {
self.reconnectFrequencySec = SSE_RECONNECT_UPPER_LIMIT;
}
}, this.reconnectFrequencySec * 1000);
}
由于 SSE 事件被馈送到主题/操作,因此连接是否丢失并不重要,因为至少最后一个事件保留在主题或存储中。然后可以静默尝试重新连接,并且当发送新数据时,会无缝处理。