ReactJs UI 中的 Spring webflux 数据 [英] Spring webflux data in ReactJs UI

查看:64
本文介绍了ReactJs UI 中的 Spring webflux 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩 spring webflux.我创建了一个项目,该项目将侦听 mongo 上限集合并在数据出现时返回数据流.
我在我的存储库方法中使用 @Tailable.

I am playing around with spring webflux. I have created a project which would listen on a mongo capped collection and return the flux of data as and when it comes.
I am using @Tailablein my repository method.

我的控制器看起来像这样

My controller looks like this

@GetMapping("/findall")
  public Flux<Product>> findAll() {
    return productRepository.findAllProducts().;
 }

这工作得很好.我通过添加一个 doOnNext(...) 对此进行了测试,每当有一个新项目添加到我的上限集合中时,doOnNext 中的消费者就会被执行.

This is working perfectly fine. I tested this by addind a doOnNext(...), Whenever there is a new item added to my capped collection, consumer inside the doOnNext is executed.

现在我希望它显示在浏览器上.我想使用 ReactJs(我对前端完全陌生).

Now I want this to be displayed on the browser. And I wanted to do with ReactJs(I am completely new to frontend).

到目前为止,我找不到任何方法在浏览器中显示通量数据.我可以通过哪些选择来实现这一目标.

So far, I couldn't find any way to display the flux data in browser. What are the options by which I can achieve this.

我尝试过这样的 SSE(服务器发送事件)

I tried SSE(Server Sent Event) like this

 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
            })
        });
 }

这工作得很好,但要让它工作,我不得不像这样更改我的服务器端代码

This works perfectly fine, but for this to work, I had to change my server side code like this

 @GetMapping("/findall")
  public Flux<ServerSentEvent<Product>> findAll() {
    return productRepository.findAllProducts().map(data -> ServerSentEvent.<Product>builder().event("product").data(data).build());
  }

这在我看来有点紧耦合,因为 UI 应该知道要监听的事件类型('product').

This, in my opinion is a bit tightly coupled because, UI should know the event type('product') to listen to.

是否有其他方法可以处理来自 UI 端的事件流(尤其是使用 reactjs)?

Is there any other way to handle stream of events from UI side(particularly with reactjs) ?

推荐答案

您不应该为了将数据流式传输到浏览器而更改控制器.以下代码片段应该可以工作:

You shouldn't have to change your controller in order to stream data to the browser. The following code snippet should work:

@GetMapping(path="/findall", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
@ResponseBody
public Flux<Product>> findAll() {
    return productRepository.findAllProducts();
}

您可以在本次研讨会此示例应用 如果您想查看完整的工作示例.

You can see this feature being used in this workshop and this sample app if you'd like to see a complete working examples.

这篇关于ReactJs UI 中的 Spring webflux 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆