服务器使用 Spring WebFlux 和 EventSource 发送事件

Server Sent Events using Spring WebFlux and EventSource

我正在处理服务器发送的事件。

参考Link:http://sinhamohit.com/writing/spring-boot-reactive-sse

以上示例包括带有 Spring Boot 和 WebFlux 的 SSE。

是否有 Spring WebFlux 和 HTML5 EventSource 可用的示例?

使用 WebFlux 创建简单的项目。 以下是服务器发送事件的控制器方法:

@GetMapping(value = "/notifyonEvent", produces = 
MediaType.TEXT_EVENT_STREAM_VALUE)  
public Flux<String> getData() {
Random r = new Random();
int low = 0;
int high = 50;
return Flux.fromStream(Stream.generate(() -> r.nextInt(high - low) + low)
    .map(s -> String.valueOf(s))
    .peek((msg) -> {
        LOGGER.info(msg);
    }))
    .map(s -> s)
    .delayElements(Duration.ofSeconds(1));
}

客户端

var source = new EventSource("YOURAPP_URL/notifyonEvent");
source.onmessage = function(event) {
  console.log(event.data);
};