我需要在Spring Boot中服务器发送事件时从SQL数据库向用户发送通知。我已经使用SseEmitter来实现这一点。
1) @GetMapping(value = "/v2/user/notifications/event",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public ResponseEntity<SseEmitter> sendNotification(@RequestHeader(value = "Authorization") final String token) {
HttpHeaders headers = new HttpHeaders();
headers.add("Connection","keep-alive");
headers.add("Cache-Control", "no-cache");
List<HttpStatus> httpStatuses = new ArrayList<>();
httpStatuses.add(0, HttpStatus.OK);
SseEmitter sseEmitter = new SseEmitter(Long.MAX_VALUE);
Integer nextEventFireTime = appConfig.getConfiguration().getInteger("sse.nextEventFireTime");
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(Constants.MAX_THREAD_POOL_SSE);
scheduledExecutorService.scheduleAtFixedRate(() -> {
try {
service.sendNotification(sseEmitter, token);
} catch (BaseException e) {
httpStatuses.add(0, HttpStatus.INTERNAL_SERVER_ERROR);
sseEmitter.completeWithError(e);
scheduledExecutorService.shutdown();
}
} , 0, nextEventFireTime, TimeUnit.SECONDS);
return new ResponseEntity<>(sseEmitter, headers, httpStatuses.get(0));
}
* nextEventFireTime配置为15
2)@Override
public synchronized void sendNotification(SseEmitter emitter, String token) throws BaseException {
NotificationMetadata notificationMetadata =
getUnreadNotificationCount(token);
List<Notification2> notificationList;
notificationList =
getSseNotifications(token);
SseEmitter.SseEventBuilder event = SseEmitter.event();
NotificationResponse2 notificationResponse2 = new NotificationResponse2();
notificationResponse2.setData(notificationList);
notificationResponse2.setMetadata(notificationMetadata);
event.name(Constants.SSE_EVENT_NAME).data(notificationResponse2)
.build();
try {
emitter.send(event.reconnectTime(15000L));
} catch (Exception e) {
throw new BaseException("Failed to send notification event.. "+e.getMessage(), Constants.ERROR_CODE_INTERNAL_ERROR,
"sendNotification", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
客户端正在等待响应,当db中没有用于通知的数据但计数查询正在获取数据时,客户端花了将近17分钟,而在有数据的情况下,还需要4-5分钟才能给出响应。
我是第一次使用SseEmitter,并且在调试服务器时执行了代码,但响应仍未决。
有人可以帮助我解决这个问题吗?