【发布时间】:2020-11-22 23:17:00
【问题描述】:
我在 SpringBoot 应用程序中有以下代码:
class MySse {
public Mono<ServerResponse> emitEvents(ServerRequest request){
return ServerResponse.ok()
.contentType(MediaType.TEXT_EVENT_STREAM)
.body(Mono.from(Flux.interval(Duration.ofSeconds(1))
.map(sequence -> ServerSentEvent.builder()
.id(String.valueOf(sequence))
.event("periodic-event")
.data("SSE - " + LocalTime.now().toString())
.build())), ServerSentEvent.class);
}
}
@Configuration
public class MyRoutesConfiguration {
@Autowired
@Bean
RouterFunction<ServerResponse> sseRoute(MySse mySse) {
return route(path("/sse").and(method(HttpMethod.GET)), MySse ::emitEvents)
;
}
@Bean
public MySse mySse() {
return new MySse();
}
}
如果我导航到 http://localhost(上面没有显示路由,但它可以工作) 从那里我在 Chrome 中打开 DevTools 并输入以下 JavaScript 代码:
const evtSource = new EventSource("sse/");
evtSource.onmessage = function(event) {
console.log(event.data);
}
但是什么都没有打印出来……
MySse::emitEvent 中的 map(...) lambda 中的断点每秒被命中
但是在浏览器的 JS 控制台中什么都没有打印出来。
如果我访问 http://localhost/sse 我会得到以下响应:
id:0
event:periodic-event
data:SSE - 20:17:12.972706400
【问题讨论】:
-
a
Mono<ServerResponse>是带有单个响应的单个请求。您需要返回Flux才能流式传输数据。
标签: java spring-boot spring-webflux