Server-sent events, SSE is an easy way to send continuous data from server-side to browsers. Its text-oriented format makes it easy to parse in the browsers. With Spring 5 WebFlux, we can easily send events. When the return type of a controller method is
Flux<ServerSentEvent>, the response will be sent following SSE spec.
The code below is a controller that sends random numbers using SSE. Random numbers are generated every second. We can use class
ServerSentEvent.Builder to build
ServerSentEvent objects. For each
ServerSentEvent object, we specify the event type
random, event ID and data.
After the server is started, we can use
curl to test it, e.g.
curl http://localhost:8080/sse/randomNumbers. See the output below.