Along with the Server API for SSE, JAX-RS 2.1 (part of Java EE 8) also has an equivalent client side API
Here is a quick peek – you can grab the project from Github
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Singleton | |
@Startup | |
public class ProgrammaticSSEClient { | |
Client sseClient; | |
WebTarget target; | |
@Resource | |
TimerService tsvc; | |
@PostConstruct | |
public void init() { | |
this.sseClient = ClientBuilder.newClient(); | |
this.target = this.sseClient.target("https://sse.now.sh"); | |
tsvc.createSingleActionTimer(15000, null); | |
System.out.println("SSE client timer created"); | |
eventSource = SseEventSource.target(target).build(); | |
System.out.println("SSE Event source created…….."); | |
} | |
SseEventSource eventSource; | |
@Timeout | |
public void client() { | |
System.out.println("SSE Client triggered in thread "+ Thread.currentThread().getName()); | |
try { | |
eventSource.register((sseEvent) | |
-> { | |
System.out.println("Events received in thread " + Thread.currentThread().getName()); | |
System.out.println("SSE event recieved —– " + sseEvent.readData()); | |
}, | |
(e) -> e.printStackTrace()); | |
eventSource.open(); | |
System.out.println("Source open ????? " + eventSource.isOpen()); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
@PreDestroy | |
public void close() { | |
eventSource.close(); | |
System.out.println("Closed SSE Event source.."); | |
sseClient.close(); | |
System.out.println("Closed JAX-RS client.."); | |
} | |
} |
To summarize
- we use a
@Singleton
EJB with@Startup
- during initialization
- create a single action (one time)
Timer
i.e.@PostConstruct
- and instantiate the
SSEEventSource
– its a public SSE source
- create a single action (one time)
- when the timer expires, the
@Timeout
annotated method gets triggered- opens the SSE connection
- prints them out – this action is registered as a callback (written as a Java 8 lamda in this case)
- Execution thread pool(s) – notice this in the logs
- the timer itself is triggered in the EJB thread pool
- SSE event callbacks are executed in the
ManagedExecutorService
thread pool (thanks toJava EE Concurrency Utilities
)
To run using Docker
Refer README
Further reading
Cheers!