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



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

参考链接: 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);
};

最新更新