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

◇◆丶佛笑我妖孽 提交于 2019-12-22 08:24:19

问题


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, my main thread of execution finishes before all requests are processed, unless I add a long Thread.sleep().

With CompletableFutures you can use: CompletableFuture.allOf(futures).join();

Is there a way to wait for all Mono's to complete ?


回答1:


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<User> one = this.webClient...
Mono<Account> two = this.webClient...
Mono<Book> three = this.webClient...

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


来源:https://stackoverflow.com/questions/50740795/how-to-wait-for-all-requests-to-complete-with-spring-5-webclient

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