how to wait for all requests to complete with Spring 5 WebClient?

前端 未结 1 1592
孤独总比滥情好
孤独总比滥情好 2021-02-20 05:15

I have a simple Java program that sends multiple requests with Spring WebClient. Each returns a mono, and I am using response.subscribe() to check the result.

However, m

1条回答
  •  离开以前
    2021-02-20 06:05

    As explained in the Project Reactor documentation, nothing happens until you subscribe to a Publisher. That operation returns an instance of Disposable, meaning that operation may still be ongoing at that point.

    If you're not in the middle of a non-blocking reactive pipeline (for example, an HTTP request/response exchange or a batch operation) and you need to wait for the completion of that pipeline before exiting the VM - then you can block(). This is actually one of the few "allowed" use cases for that.

    Your question doesn't really explain what you mean by "check the response". Here, we'll just get POJOs (if the HTTP response status is not 200 or if we can't deserialize the response, an error signal will be sent). In your example, you could have something like:

    Mono one = this.webClient...
    Mono two = this.webClient...
    Mono three = this.webClient...
    
    // we want all requests to happen concurrently
    Mono all = Mono.when(one, two, three);
    // we subscribe and then wait for all to be done
    all.block();
    

    0 讨论(0)
提交回复
热议问题