Issue
Hi when am loading the page the first subscription request for SSE is working fine. but when SSE timeout and go for subscribe again am getting 503 error.
My backend code:
@RestController
@Slf4j
public class UpdateNotification {
@Autowired
SseService sseService;
@GetMapping(value = "/api/v1/item/subscription", consumes = MediaType.ALL_VALUE, produces = MediaType.ALL_VALUE)
public SseEmitter subscribe(@RequestParam("id") long id) throws InterruptedException, IOException {
SseEmitter emitter = new SseEmitter();
sseService.add(id, emitter);
emitter.onCompletion(() -> sseService.remove(id, emitter));
emitter.onError((ex)->log.info("Error>> "+ ex.getMessage()));
return emitter;
}
@Async
public void produce(@RequestBody final MessageDTO message) {
GetData(message);
}
public void GetData(final MessageDTO message) {
sseService.getSsEmitters(message.getItemDTO().getId()).forEach((SseEmitter emitter) -> {
try {
emitter.send(message.getPrice(), MediaType.APPLICATION_JSON);
} catch (IOException e) {
emitter.complete();
sseService.remove(message.getId(), emitter);
e.printStackTrace();
}
});
}
}
my frontend javascript code
function initialize() {
var itemId=$("#itemId").text();
const eventSource = new EventSource('/api/v1/item/subscription?id='+itemId);
eventSource.onmessage = e => {
const msg = e.data;
$("#price").text(msg);
Notification.requestPermission(function () {
if (Notification.permission === 'granted') {
// user approved.
var text = msg;
var notification = new Notification('Notification Alert!', {body: text});
setTimeout(notification.close(), 6 * 1000) // close in 5 sec
} else if (Notification.permission === 'denied') {
// user denied.
} else { // Notification.permission === 'default'
// user didn’t make a decision.
// You can’t send notifications until they grant permission.
}
});
};
eventSource.onopen = e => console.log('open');
eventSource.onerror = e => {
if (e.readyState == EventSource.CLOSED) {
console.log('close');
} else {
console.log(e);
}
};
eventSource.addEventListener('second', function (e) {
console.log('second', e.data);
}, false);
}
window.onload = initialize();
first request send request successfully
When timeout happen subscription request automatic generate which throwing 503 error
I have no idea why am getting 503 on subscribe again after timeout. Please help me to solve this problem.
Solution
I fixed that problem by moving GetData(message) method from controller class to service class with implementation now it working fine. This is best way to stay with apache tomcat while making reactive programming in springboot. Or you can go with spring reactive(Webflux) which run at netty server.
Answered By - deepak maurya
Answer Checked By - Cary Denson (JavaFixing Admin)