我正在使用EventSource和SSE向用户推送通知。我的身份验证基于JWT令牌,该令牌每10分钟失效一次。到期后,我需要关闭以前的EventSource并开始一个新的EventSource。但是,我无法在客户端识别超时事件。
客户端代码:
let eventSource = new EventSourcePolyfill(AppUrl.NEW_NOTIFICATIONS, { headers: { Authorization: 'Bearer ' + this.authService.getAccessToken() } });
eventSource.onmessage = (message) => {
this.store.dispatch(NotificationActionFactory.addNotifications.createNew({ notifications: JSON.parse(message.data) }));
};
eventSource.onopen = (a) => {
console.log('Connection Open');
};
eventSource.onerror = (e) => {
if(e.target.readyState == eventSource.CLOSED){
eventSource.close();
console.log('Connection closed');
}else{
console.log('error message');
}
};
服务器端代码:
@RequestMapping(value = "/app/notifications/new", method = RequestMethod.GET)
public ResponseEntity<SseEmitter> streamNotification() {
Long timeoutTime = DataServiceUtil.getTokenTimeoutTime(credentialProvider.getExpiryTime());
logger.debug("The timeout is {}", timeoutTime);
final SseEmitter emitter = new SseEmitter(60000L);
emitter.onTimeout(() -> {
emitter.complete();
});
service.addEventToStore(credentialProvider.getUserId(), emitter);
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("X-Accel-Buffering",
"no");
return ResponseEntity.ok()
.headers(responseHeaders).body(emitter);
}