我正在玩 spring webflux。我创建了一个项目,它将监听 mongo 上限的集合并在数据到来时返回数据流。
我正在使用@Tailable
在我的存储库方法中。
我的 Controller 看起来像这样
@GetMapping("/findall")
public Flux<Product>> findAll() {
return productRepository.findAllProducts().;
}
这工作得很好。我通过添加 doOnNext(...)
对此进行了测试,每当有新项目添加到我的上限集合中时,都会执行 doOnNext 内的消费者。
现在我希望它显示在浏览器上。我想用 ReactJs 来做(我对前端完全陌生)。
到目前为止,我找不到任何方法在浏览器中显示通量数据。我可以通过哪些选择来实现这一目标。
我尝试了这样的SSE(服务器发送事件)
componentDidMount() {
this.eventSource = new EventSource('http://localhost:8080/findall');
this.eventSource.addEventListener('product', (data) => {
let json = JSON.parse(data.data)
this.state.products.push(json.name)
this.setState ( {
products : this.state.products
})
});
}
这工作得很好,但是为了让它工作,我必须像这样改变我的服务器端代码
@GetMapping("/findall")
public Flux<ServerSentEvent<Product>> findAll() {
return productRepository.findAllProducts().map(data -> ServerSentEvent.<Product>builder().event("product").data(data).build());
}
在我看来,这有点紧密耦合,因为 UI 应该知道要监听的事件类型(“产品”)。
是否还有其他方法可以处理 UI 端的事件流(特别是 reactjs
)?
最佳答案
您不必更改 Controller 即可将数据流式传输到浏览器。以下代码片段应该可以工作:
@GetMapping(path="/findall", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Product>> findAll() {
return productRepository.findAllProducts();
}
您可以看到此功能在 this workshop 中使用和 this sample app如果您想查看完整的工作示例。
关于reactjs - ReactJs UI 中的 Spring webflux 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48888997/