Server Sent Events, send event with data when there is a change in DB (Spring)

Viewed 450

in my project i have a thread that every n minutes call a external service and write in a h2 database by a his service/dao, the operation are Insert and Update Row, i need to notify a other mvc layer in the same application, the 2 layers use the same entities, the second mvc layer send datas to a angular application via SSE, in my controller there is a endpoint with something like this:

@GetMapping("/sse")
public SseEmitter streamSseMvc() {
    List<Message> messages = MessageRepository.findAll();
    SseEmitter emitter = new SseEmitter();
    ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
    sseMvcExecutor.execute(() -> {
        try {
            for (int i = 0; i!=messages.size; i++) {
                SseEventBuilder event = SseEmitter.event()
                  .data(messages.get(i))
                  .id(String.valueOf(i));
                emitter.send(event);
                Thread.sleep(1000);
            }
        } catch (Exception ex) {
            emitter.completeWithError(ex);
        }
    });
    return emitter;
}

My goal is to always send new messages to the application in Angular, without refreshing the page that calls this endpoint and be in real time. I thought of something that would notify a method when the other layer write on H2 DB, for example notify the method of the service of this controller, and then in that method send the event which it must intercept by the SSeEmitter of this controller. But i dont know how implement it. I dont want use Trigger in DB and im using Spring 4 ...

Thanks.

0 Answers
Related