我正在玩spring webflux。我创建了一个项目,该项目将监听mongo封顶的收集,并在收到数据时返回数据流量。
我正在使用
@Tailable
在我的存储库方法中。
我的控制器看起来像这样
@GetMapping("/findall")
public Flux<Product>> findAll() {
return productRepository.findAllProducts().;
}
这工作非常好。我用addind a测试了这个
doOnNext(...)
,每当有新项目添加到我的capped collection中时,将执行doOnNext中的consumer。
现在我想在浏览器上显示它。我想使用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
) ?