In the Mozilla description for server sent events there is a note:
A colon as the first character of a line is in essence a comment, and is ignored. Note: The comment line can be used to prevent connections from timing out; a server can send a comment periodically to keep the connection alive.
So periodically sending comments can keep the connection alive. So how do we send a comment?
Well spring has the class ServerSentEvent that has the function ServerSentEvent#comment. So if we use this class in combination with for instance Flux#interval we can merge in events containing only the comments keep alive.
Here is an example from a project i built a while back
@Bean
public RouterFunction<ServerResponse> foobars() {
return route()
.path("/api", builder -> builder
.GET("/foobar/{id}", accept(TEXT_EVENT_STREAM), request -> ok()
.contentType(MediaType.TEXT_EVENT_STREAM)
.header("Cache-Control", "no-transform")
.body(Flux.merge(foobarHandler.stream(request.pathVariable("id")),
Flux.interval(Duration.ofSeconds(15)).map(aLong -> ServerSentEvent.<List<FoobarResponse>>builder()
.comment("keep alive").build())), new ParameterizedTypeReference<ServerSentEvent<List<FoobarResponse>>>(){}))
.build();
}