Server-Sent Events
Juneau REST Server now includes SSE response helpers for event-at-a-time streaming endpoints.
For the SSE serializer, parser and event types themselves, see SSE.
RestResponse.sse() helper
Use RestResponse.sse() to configure an SSE response and emit events without manually juggling writer state:
@RestGet(path="/stream", serializers=SseSerializer.class)
public void stream(RestResponse res) throws Exception {
try (var sse = res.sse().heartbeat(Duration.ofSeconds(15))) {
sse.sendEvent("tick", "one");
sse.comment("ping");
sse.sendEvent(new SseEvent("tick", "two"));
sse.flush();
}
}
The helper sets:
Content-Type: text/event-streamCache-Control: no-cacheX-Content-Type-Options: nosniffContent-Encoding: identity
Broadcaster pattern
Use SseBroadcaster and SseSubscription for fan-out from one producer to many subscribers.
@RestGet(path="/broadcast", serializers=SseSerializer.class)
public void broadcast(RestRequest req, RestResponse res, SseBroadcaster broadcaster) throws Exception {
var id = req.getHttpServletRequest().getRequestId();
var subscription = broadcaster.subscribe(id);
try (var sse = res.sse().heartbeat(Duration.ofSeconds(15))) {
sse.sendFrom(subscription);
} finally {
subscription.close();
}
}
When a subscriber queue is full, the in-memory broadcaster drops the oldest event so recent events continue to flow.