Spring 5 WebClient如何等待所有请求完成? [英] how to wait for all requests to complete with Spring 5 WebClient?

查看:576
本文介绍了Spring 5 WebClient如何等待所有请求完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Java程序,可以通过Spring WebClient发送多个请求.每个返回一个单声道,我正在使用response.subscribe()来检查结果.

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.

但是,除非我添加一个很长的Thread.sleep(),否则我的执行主线程会在所有请求得到处理之前完成.

However, my main thread of execution finishes before all requests are processed, unless I add a long Thread.sleep().

通过CompletableFutures,您可以使用:CompletableFuture.allOf(futures).join();

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

有没有办法等待所有Mono的完成?

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

推荐答案

中所述,直到您subscribePublisher都不会发生.该操作将返回Disposable的实例,这意味着该操作可能在此时仍在进行.

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.

如果您不在非阻塞式反应式管道的中间(例如,HTTP请求/响应交换或批处理操作),并且需要在退出虚拟机之前等待该管道的完成-然后您可以block().实际上,这是为数不多的允许"用例之一.

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.

您的问题并未真正解释检查响应"的含义.在这里,我们将仅获得POJO(如果HTTP响应状态不是200或无法反序列化响应,则将发送错误信号). 在您的示例中,您可能会有类似的内容:

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

这篇关于Spring 5 WebClient如何等待所有请求完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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