Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// The two things I see in every SSE example:
@GET @Produces(MediaType.SERVER_SENT_EVENTS)
public void eventStream(@Context SseEventSink eventSink, @Context Sse sse) {
// starting a separate thread to handle the complete request within
// the context of the method
executor.execute(() -> {
// try-with-resources: closing the resource also in the method
try(SseEventSink sink = eventSink) {
eventSink.onNext(sse.newEvent("event1"));
// don't think the close (which is in the blog) is needed?
} catch (IOException e) { /* handle exception */ }
});
}
// my usual case
private static final Map<String, SseEventSink> openListeners = new HashMap<>(); // hmmm... cluster anybody?
@GET @Path("monitor") @Produces(MediaType.SERVER_SENT_EVENTS)
public void startListening(@Context SseEventSink eventSink, @Context Sse sse) {
String key = RandomUtils.randomString();
// store the eventSink, no closing means the method emits a warning
openListeners.put(key, eventSink);
// have some other process know where to find the eventSink
otherProcess.registerCallback("callback/"+key);
// no action here
}
// some other process has done something and wants the user to know,
// it calls this method. Other than the callback that was registered
// the two calls are unrelated
@GET @Path("callback/{key}")
public void callback(@PathParam("key") String key, @Context Sse sse) {
try {
SseEventSink eventSink = openListeners.get(key);
eventSink.onNext(sse.newEvent("event1"));
// optionally
eventSink.close();
} catch (IOException e) { /* handle exception */ }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment