Video in progress

How do you write an SSE endpoint in Spring WebFlux, and how does it differ from SseEmitter in Spring MVC?

In WebFlux the controller returns a Flux<ServerSentEvent<T>> and the framework sends each element as an event. You don't store emitters by hand or catch send and IOException; when the client leaves, the subscription is cancelled automatically.

📖 Answer

@RestController
public class PriceStreamController {

    private final Sinks.Many<Price> sink = Sinks.many().multicast().directBestEffort();

    @GetMapping(value = "/api/prices/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Price>> stream() {
        Flux<ServerSentEvent<Price>> prices = sink.asFlux()
                .map(p -> ServerSentEvent.builder(p).event("price").id(String.valueOf(p.seq())).build());

        Flux<ServerSentEvent<Price>> heartbeat = Flux.interval(Duration.ofSeconds(20))
                .map(i -> ServerSentEvent.<Price>builder().comment("ping").build());

        return Flux.merge(prices, heartbeat);
    }

    public void publish(Price p) {
        sink.tryEmitNext(p);
    }
}

The differences:

  • In MVC you manage the list of emitters, cleanup and thread safety yourself; in WebFlux all of that lives inside Flux and Sinks.
  • When the client closes the connection, WebFlux sends a cancel signal, and you clean up with doOnCancel. In MVC you only learn about it from an exception on the next send.
  • directBestEffort drops a message for a slow subscriber that couldn't keep up, and doesn't wait for the others. That's right for a price or exchange-rate stream, but for order statuses losing a message may be unacceptable.

If the project is entirely MVC, there's no need to switch to WebFlux just for SSE. Returning a Flux also works in an MVC controller if Reactor is on the classpath.