org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder Java Examples

The following examples show how to use org.springframework.web.servlet.mvc.method.annotation.SseEmitter.SseEventBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringSseEmitterTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@GetMapping("/sse")
public SseEmitter streamSseMvc() {
    final SseEmitter emitter = new SseEmitter();
    final ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
    
    sseMvcExecutor.execute(() -> {
        try {
            for (int eventId = 1; eventId <= 5; ++eventId) {
                SseEventBuilder event = SseEmitter.event()
                    .id(Integer.toString(eventId))
                    .data(new Book("New Book #" + eventId, "Author #" + eventId), MediaType.APPLICATION_JSON)
                    .name("book");
                emitter.send(event);
                Thread.sleep(100);
            }
        } catch (Exception ex) {
            emitter.completeWithError(ex);
        }
    });
    
    return emitter;
}
 
Example #2
Source File: SseEmitterController.java    From tutorials with MIT License 6 votes vote down vote up
@GetMapping("/stream-sse-mvc")
public SseEmitter streamSseMvc() {
    SseEmitter emitter = new SseEmitter();
    ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();

    sseMvcExecutor.execute(() -> {
        try {
            for (int i = 0; true; i++) {
                SseEventBuilder event = SseEmitter.event()
                    .data("SSE MVC - " + LocalTime.now()
                        .toString())
                    .id(String.valueOf(i))
                    .name("sse event - mvc");
                emitter.send(event);
                Thread.sleep(1000);
            }
        } catch (Exception ex) {
            emitter.completeWithError(ex);
        }
    });
    return emitter;
}