Search code examples
server-sent-eventsspring-webfluxeventsource

Server Sent Events using Spring WebFlux and EventSource


I am working on Server Sent Events.

Reference Link: http://sinhamohit.com/writing/spring-boot-reactive-sse

The above example includes SSE with Spring Boot and WebFlux.

Is there any example available with Spring WebFlux and HTML5 EventSource?


Solution

  • Create simple project with WebFlux. Below is controller method for server sent event:

    @GetMapping(value = "/notifyonEvent", produces = 
    MediaType.TEXT_EVENT_STREAM_VALUE)  
    public Flux<String> getData() {
    Random r = new Random();
    int low = 0;
    int high = 50;
    return Flux.fromStream(Stream.generate(() -> r.nextInt(high - low) + low)
        .map(s -> String.valueOf(s))
        .peek((msg) -> {
            LOGGER.info(msg);
        }))
        .map(s -> s)
        .delayElements(Duration.ofSeconds(1));
    }
    

    Client side

    var source = new EventSource("YOURAPP_URL/notifyonEvent");
    source.onmessage = function(event) {
      console.log(event.data);
    };