Server sent events using sseemitter taking more time to respond












0















I have a requirement to send notification from SQL database to the user as Server sent events in Spring Boot. I have used SseEmitter to implement this.



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 is configured as 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);
}
}


The client is waiting for the response and it is taking close to 17 minutes when there is no data in db for notification but count query is fetching the data and when there is data then also it is taking 4-5 minutes to give the response.



I am using SseEmitter first time and when I debug the code at server is executed but the response is still pending.



Can someone help me with this issue?










share|improve this question

























  • Why is the method synchronized ? also why recreate a ScheduledExecutorService you should better configure a TaskScheduler and reuse that (now you run the risk in creating a lot of threads which might actually slow things down). You are also rebuilding the event twice not sure why you are doing that either.

    – M. Deinum
    Nov 20 '18 at 7:17











  • I have used synchronized because there is 2 query to get data and I want one thread to finish execution before other thread interrupts. I am not using Task Scheduler because SSE should transfer data only when one registration is done from a user and I am creating a event then doing build in the next line.

    – Priyanka Mourya
    Nov 25 '18 at 13:01











  • The result of the call to build is ignored hence that is event 1... Then you call reconnectTime which creates another event, hence you are creating multiple events. Also if you want it single threaded then why even bother making it async? Seems like a lot of work for absolutely no gain.

    – M. Deinum
    Nov 26 '18 at 7:53
















0















I have a requirement to send notification from SQL database to the user as Server sent events in Spring Boot. I have used SseEmitter to implement this.



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 is configured as 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);
}
}


The client is waiting for the response and it is taking close to 17 minutes when there is no data in db for notification but count query is fetching the data and when there is data then also it is taking 4-5 minutes to give the response.



I am using SseEmitter first time and when I debug the code at server is executed but the response is still pending.



Can someone help me with this issue?










share|improve this question

























  • Why is the method synchronized ? also why recreate a ScheduledExecutorService you should better configure a TaskScheduler and reuse that (now you run the risk in creating a lot of threads which might actually slow things down). You are also rebuilding the event twice not sure why you are doing that either.

    – M. Deinum
    Nov 20 '18 at 7:17











  • I have used synchronized because there is 2 query to get data and I want one thread to finish execution before other thread interrupts. I am not using Task Scheduler because SSE should transfer data only when one registration is done from a user and I am creating a event then doing build in the next line.

    – Priyanka Mourya
    Nov 25 '18 at 13:01











  • The result of the call to build is ignored hence that is event 1... Then you call reconnectTime which creates another event, hence you are creating multiple events. Also if you want it single threaded then why even bother making it async? Seems like a lot of work for absolutely no gain.

    – M. Deinum
    Nov 26 '18 at 7:53














0












0








0








I have a requirement to send notification from SQL database to the user as Server sent events in Spring Boot. I have used SseEmitter to implement this.



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 is configured as 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);
}
}


The client is waiting for the response and it is taking close to 17 minutes when there is no data in db for notification but count query is fetching the data and when there is data then also it is taking 4-5 minutes to give the response.



I am using SseEmitter first time and when I debug the code at server is executed but the response is still pending.



Can someone help me with this issue?










share|improve this question
















I have a requirement to send notification from SQL database to the user as Server sent events in Spring Boot. I have used SseEmitter to implement this.



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 is configured as 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);
}
}


The client is waiting for the response and it is taking close to 17 minutes when there is no data in db for notification but count query is fetching the data and when there is data then also it is taking 4-5 minutes to give the response.



I am using SseEmitter first time and when I debug the code at server is executed but the response is still pending.



Can someone help me with this issue?







java sql spring-boot push-notification server-sent-events






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 6:40









GauravRai1512

58811




58811










asked Nov 20 '18 at 5:29









Priyanka MouryaPriyanka Mourya

11




11













  • Why is the method synchronized ? also why recreate a ScheduledExecutorService you should better configure a TaskScheduler and reuse that (now you run the risk in creating a lot of threads which might actually slow things down). You are also rebuilding the event twice not sure why you are doing that either.

    – M. Deinum
    Nov 20 '18 at 7:17











  • I have used synchronized because there is 2 query to get data and I want one thread to finish execution before other thread interrupts. I am not using Task Scheduler because SSE should transfer data only when one registration is done from a user and I am creating a event then doing build in the next line.

    – Priyanka Mourya
    Nov 25 '18 at 13:01











  • The result of the call to build is ignored hence that is event 1... Then you call reconnectTime which creates another event, hence you are creating multiple events. Also if you want it single threaded then why even bother making it async? Seems like a lot of work for absolutely no gain.

    – M. Deinum
    Nov 26 '18 at 7:53



















  • Why is the method synchronized ? also why recreate a ScheduledExecutorService you should better configure a TaskScheduler and reuse that (now you run the risk in creating a lot of threads which might actually slow things down). You are also rebuilding the event twice not sure why you are doing that either.

    – M. Deinum
    Nov 20 '18 at 7:17











  • I have used synchronized because there is 2 query to get data and I want one thread to finish execution before other thread interrupts. I am not using Task Scheduler because SSE should transfer data only when one registration is done from a user and I am creating a event then doing build in the next line.

    – Priyanka Mourya
    Nov 25 '18 at 13:01











  • The result of the call to build is ignored hence that is event 1... Then you call reconnectTime which creates another event, hence you are creating multiple events. Also if you want it single threaded then why even bother making it async? Seems like a lot of work for absolutely no gain.

    – M. Deinum
    Nov 26 '18 at 7:53

















Why is the method synchronized ? also why recreate a ScheduledExecutorService you should better configure a TaskScheduler and reuse that (now you run the risk in creating a lot of threads which might actually slow things down). You are also rebuilding the event twice not sure why you are doing that either.

– M. Deinum
Nov 20 '18 at 7:17





Why is the method synchronized ? also why recreate a ScheduledExecutorService you should better configure a TaskScheduler and reuse that (now you run the risk in creating a lot of threads which might actually slow things down). You are also rebuilding the event twice not sure why you are doing that either.

– M. Deinum
Nov 20 '18 at 7:17













I have used synchronized because there is 2 query to get data and I want one thread to finish execution before other thread interrupts. I am not using Task Scheduler because SSE should transfer data only when one registration is done from a user and I am creating a event then doing build in the next line.

– Priyanka Mourya
Nov 25 '18 at 13:01





I have used synchronized because there is 2 query to get data and I want one thread to finish execution before other thread interrupts. I am not using Task Scheduler because SSE should transfer data only when one registration is done from a user and I am creating a event then doing build in the next line.

– Priyanka Mourya
Nov 25 '18 at 13:01













The result of the call to build is ignored hence that is event 1... Then you call reconnectTime which creates another event, hence you are creating multiple events. Also if you want it single threaded then why even bother making it async? Seems like a lot of work for absolutely no gain.

– M. Deinum
Nov 26 '18 at 7:53





The result of the call to build is ignored hence that is event 1... Then you call reconnectTime which creates another event, hence you are creating multiple events. Also if you want it single threaded then why even bother making it async? Seems like a lot of work for absolutely no gain.

– M. Deinum
Nov 26 '18 at 7:53












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386765%2fserver-sent-events-using-sseemitter-taking-more-time-to-respond%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53386765%2fserver-sent-events-using-sseemitter-taking-more-time-to-respond%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to send String Array data to Server using php in android

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

Is anime1.com a legal site for watching anime?