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

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

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

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

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

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

the Project Reactor documentation 中所述,在您 subscribePublisher 之前什么都不会发生。该操作 returns 是 Disposable 的一个实例,这意味着该操作可能仍在进行中。

如果您不在非阻塞反应管道的中间(例如,HTTP request/response 交换或批处理操作)并且您需要等待该管道完成后再退出VM - 然后你可以 block()。这实际上是为数不多的 "allowed" 用例之一。

你的问题并没有真正解释你所说的 "check the response" 的意思。在这里,我们将只获取 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();