Spring 5 WebFlux with Server-Sent Events

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuples;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
@RestController
@RequestMapping("/sse")
public class SseController {
@GetMapping("/randomNumbers")
public Flux<ServerSentEvent<Integer>> randomNumbers() {
return Flux.interval(Duration.ofSeconds(1))
.map(seq -> Tuples.of(seq, ThreadLocalRandom.current().nextInt()))
.map(data -> ServerSentEvent.<Integer>builder()
.event("random")
.id(Long.toString(data.getT1()))
.data(data.getT2())
.build());
}
}

After the server is started, we can use curl to test it, e.g. curl http://localhost:8080/sse/randomNumbers. See the output below.

1
2
3
4
5
6
7
8
9
10
11
id:0
event:random
data:751025203
id:1
event:random
data:-1591883873
id:2
event:random
data:-1899224227
Comments