Jersey itself supports SSE for years, now it is standardized as a part of JAXRS 2.1.
A simple SSE example.
@Path("events")@RequestScopedpublicclassSseResource { @GET @Produces(MediaType.SERVER_SENT_EVENTS)publicvoideventStream(@ContextSse sse, @ContextSseEventSink eventSink) {// Resource method is invoked when a client subscribes to an event stream.// That implies that sending events will most likely happen from different// context - thread / event handler / etc, so common implementation of the// resource method will store the eventSink instance and the application // logic will retrieve it when an event should be emitted to the client.// sending events:eventSink.send(sse.newEvent("event1")); } }
Notice, you should declare @Produces value as text/event-stream( via MediaType.SERVER_SENT_EVENTS). SseEventSink should be request aware, Sse is helpful to build event payloads etc.
An example of SSE client.
WebTarget target =ClientBuilder.newClient().target("http://localhost:8080/jaxrs-sse/rest/events");try (SseEventSource eventSource =SseEventSource.target(target).build()) {// EventSource#register(Consumer<InboundSseEvent>)// Registered event handler will print the received message.eventSource.register(System.out::println);// Subscribe to the event stream.eventSource.open();// Consume events for just 500 msThread.sleep(500);} catch (InterruptedException e) {e.printStackTrace();}
The following is an example demonstrates the usage of SseBroadcaster, which allow you send messages to all registered clients.