Spring ReactJs 中的 webflux 数据 UI
Spring webflux data in ReactJs UI
我正在玩 spring webflux。我创建了一个项目,它将监听 mongo 上限集合和 return 数据的流动。
我在我的存储库方法中使用 @Tailable
。
我的控制器看起来像这样
@GetMapping("/findall")
public Flux<Product>> findAll() {
return productRepository.findAllProducts().;
}
这工作得很好。我通过 addind a 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 应该知道要收听的事件类型 ('product')。
是否有任何其他方法来处理来自 UI 端的事件流(特别是 reactjs
)?
您不必更改控制器即可将数据流式传输到浏览器。以下代码片段应该有效:
@GetMapping(path="/findall", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Product>> findAll() {
return productRepository.findAllProducts();
}
如果您想查看完整的工作示例,可以在 this workshop and this sample app 中看到此功能的使用。
我正在玩 spring webflux。我创建了一个项目,它将监听 mongo 上限集合和 return 数据的流动。
我在我的存储库方法中使用 @Tailable
。
我的控制器看起来像这样
@GetMapping("/findall")
public Flux<Product>> findAll() {
return productRepository.findAllProducts().;
}
这工作得很好。我通过 addind a 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 应该知道要收听的事件类型 ('product')。
是否有任何其他方法来处理来自 UI 端的事件流(特别是 reactjs
)?
您不必更改控制器即可将数据流式传输到浏览器。以下代码片段应该有效:
@GetMapping(path="/findall", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Product>> findAll() {
return productRepository.findAllProducts();
}
如果您想查看完整的工作示例,可以在 this workshop and this sample app 中看到此功能的使用。