Search code examples
spring-bootstreaming

Springboot stream


I have a springboot API which is dealing with lot of processes in backend. I need to stream the status to the frontend. Since I am new to springboot can anyone help me how to achieve this scenario.

Note - Application is going to be containerized in future and I cannot use any cloud service for this.


Solution

  • As there is not much to go off of I will try my best: If you are using Log4j2 you could simply usethe SocketAppender (external link)

    If not: I did something similar recently and you will need to somehow turn your logs into a stream. I'd advise using the information found here (non-external link)

    OutputStream Stream;
    
    @GetMapping("/stream-sse-mvc")
    public SseEmitter streamSseMvc() {
        SseEmitter emitter = new SseEmitter();
        ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
        sseMvcExecutor.execute(() -> {
            try {
                Stream.map(sequence -> SseEmitter.event()
                       .id(""))
                       .event("EVENT_TYPE")
                       .data("String.valueOf(sequence)
                       .build());
                    emitter.send(event);
                    Thread.sleep(1000); //This does not need to be here
            } catch (Exception ex) {
                emitter.completeWithError(ex);
            }
        });
        return emitter;
    }
    

    There might be better ways to reach your endpoints but without knowing what Frameworks you are using this is hard to answer. Essentially what we are doing is capturing all log output to a stream which is then broadcasted by an SSE.