|
|
This feature allows to provide Server-Sent Events in the backend and
|
|
|
to have Java clients to receive those events.
|
|
|
|
|
|
### Backend example
|
|
|
|
|
|
Interface:
|
|
|
|
|
|
public interface SseInterface {
|
|
|
@SSE(autoReconnect=20)
|
|
|
EventStream<TestPojo> status(String jobName);
|
|
|
}
|
|
|
|
|
|
* The method must have an @SSE annotation. You may control the reconnect delay here, too
|
|
|
* The method must return an `EventStream` of some payload type. This can be any type you like
|
|
|
(no streams here)
|
|
|
* Pass any arguments you like (limited support of annotations currently)
|
|
|
|
|
|
Implementation:
|
|
|
|
|
|
public class SseHandler implements SseInterface {
|
|
|
@Override
|
|
|
public EventStream<TestPojo> status(String jobName) {
|
|
|
return (EventStream<TestPojo> stream) -> {
|
|
|
//compute values, loop or wait
|
|
|
|
|
|
try {
|
|
|
TestPojo event = new TestPojo(...);
|
|
|
stream.pushEvent(event);
|
|
|
|
|
|
...
|
|
|
} catch (Throwable e) {
|
|
|
...
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
* The implementation returns a `Consumer<EventStream<Payload>>`. This will automatically converted by Java into an `EventStream<Payload>` using FunctionalInterface mechanics.
|
|
|
* The provided stream is the transport for the generated events. _Just push your events into the stream_.
|
|
|
* The consumer may be a long running task. It should check for the interrupted flag, tough
|
|
|
|
|
|
Client:
|
|
|
|
|
|
...
|
|
|
DelightConfig cfg = DelightConfigFinder.getDefaultConfigBuilder()
|
|
|
.registerFeaturesByClass(SseFeature.class)
|
|
|
.build();
|
|
|
|
|
|
String endpoint = "http://localhost:8080/example-delight-webapp/delight";
|
|
|
Delight delight = new Delight(cfg);
|
|
|
SseInterface sseService = delight
|
|
|
.connectingTo(endpoint)
|
|
|
.usingApi(SseInterface.class);
|
|
|
|
|
|
try (EventStream<TestPojo> events = sseService.status("send me events ...")) {
|
|
|
events.register(eventPayload -> {
|
|
|
System.out.printf("(SseClient)Received: '%s'\n", eventPayload);
|
|
|
},
|
|
|
ex -> { //error handler
|
|
|
System.out.print("(SseClient)Error: ");
|
|
|
ex.printStackTrace();
|
|
|
},
|
|
|
() -> { //completion handler
|
|
|
System.out.println("(SseClient)Stopped listening!");
|
|
|
});
|
|
|
events.startListening();
|
|
|
|
|
|
//receive for a while
|
|
|
Thread.sleep(45*1000);
|
|
|
}
|
|
|
... |