Spring webflux data in ReactJs UI

孤人 提交于 2019-12-11 07:31:56

问题


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

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.

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.

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

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

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


回答1:


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.



来源:https://stackoverflow.com/questions/48888997/spring-webflux-data-in-reactjs-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!