其他分享
首页 > 其他分享> > 如何等待Spring 5 WebClient完成所有请求?

如何等待Spring 5 WebClient完成所有请求?

作者:互联网

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

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

使用CompletableFutures,您可以使用:CompletableFuture.allOf(期货).join();

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

解决方法:

the Project Reactor documentation中所述,在您订阅发布者之前没有任何反应.该操作返回Disposable的实例,这意味着此时操作可能仍在进行中.

如果您不在非阻塞的反应管道中(例如,HTTP请求/响应交换或批处理操作),并且您需要在退出VM之前等待该管道的完成 – 那么您可以阻止().这实际上是为数不多的“允许”用例之一.

您的问题并没有真正解释“检查回复”的含义.在这里,我们将获得POJO(如果HTTP响应状态不是200或者如果我们不能反序列化响应,则将发送错误信号).
在您的示例中,您可以使用以下内容:

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

标签:project-reactor,spring-webflux,spring
来源: https://codeday.me/bug/20190910/1799280.html