Search code examples
javajakarta-eejax-rsserver-sent-eventsjava-ee-8

How can I asynchronously handle SSE events?


Optimally, I would like to be able to do something like this

Request request = new Request("http://someendpoint")
request.onMessage(payload -> System.out.println(payload))
request.onError(error -> error.printStackTrace())
request.onClose(() -> System.out.println("closed"))
request.onConnect(isReconnect -> System.out.println("connected"))

Obviously doesn't have to be exactly like that, just thought it would help explain what I was trying to do.

I have seen that there is some sort of support for this in Jersey. I would like to find an alternative but will use that if nothing else is available.


Solution

  • SSEs are available in JavaEE 8 through JAX-RS 2.1 in the javax.ws.rs.sse package. Unlike requests and responses which can be synchronous or asynchronous, SSEs are asynchronous by nature.

    For a demonstration of SSEs have a look at this video by David Delabassee. Your code (which is client-side only) would looks something like this:

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://someendpoint");
    
    SseEventSource eventSource = SseEventSource.target(target)
                                               .reconnectingEvery(5, TimeUnit.SECONDS)
                                               .build();
    eventSource.register(payload -> System.out.println(payload),   // Consumer<InboundSseEvent>
                         error -> error.printStackTrace(),         // Consumer<Throwable>
                         () -> System.out.println("no more events"));
    eventSource.open();
    // and eventually
    eventSource.close();
    

    There are no built-in handlers for (re)connection and closing, but you could customize something to have the same effect.

    JAX-RS 2.1 is implemented in (at least):

    • Jersey 2.26, which is included in Glassfish 5 and Payara 5 alpha/snapshot/pre-release.
    • RESTEasy 4.0.0.Beta1 (released less than a month ago) and is reported to work on Wildfly 10 and above, though I think only Wildfly 12 will implement the full JavaEE 8 (announcements change with time...).