Skip to content

Instantly share code, notes, and snippets.

@ShopifyEng
Created November 29, 2022 20:09
Simplifying Real-time Streaming at Scale with Server Sent Events: SSE_Java_client_connections
public static void process(String endpoint, String bearerToken, int numberOfSessions, long pauseTimeMs, int sessionLengthMins) throws Exception{
EventHandler handler =new EventHandler() {
@Override
public void onOpen() throws Exception {
System.out.println("Open ");
}
@Override
public void onClosed() throws Exception {
System.out.println("closed ");
}
@Override
public void onMessage(String s, MessageEvent messageEvent) throws Exception {
System.out.println("message: " + messageEvent.getData());
}
@Override
public void onComment(String s) throws Exception {
System.out.println("comment: "+s);
}
@Override
public void onError(Throwable throwable) {
throwable.printStackTrace();
}
};
EventSource.Builder builder = new EventSource.Builder(handler, URI.create(endpoint)).headers(Headers.of("Authorization","bearer "+bearerToken));
for(int i = 0; i< numberOfSessions; i++) {
TimeUnit.MILLISECONDS.sleep(pauseTimeMs);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try (EventSource eventSource = builder.build()) {
eventSource.start();
TimeUnit.MINUTES.sleep(sessionLengthMins);
}catch(Exception ex) {
ex.printStackTrace();
}
}
});
t.setDaemon(false);
t.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment