Skip to content

Instantly share code, notes, and snippets.

@vrolijken
Created March 8, 2017 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrolijken/a342094ea72c51ff82339504c7e1321c to your computer and use it in GitHub Desktop.
Save vrolijken/a342094ea72c51ff82339504c7e1321c to your computer and use it in GitHub Desktop.
// 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