如何使用Spring WebClient同时进行多个调用?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用Spring WebClient同时进行多个调用?相关的知识,希望对你有一定的参考价值。

我想同时执行3个调用,并在完成所有操作后处理结果。

我知道这可以使用AsyncRestTemplate实现,因为它在这里提到How to use AsyncRestTemplate to make multiple calls simultaneously?

但是,不推荐使用AsyncRestTemplate而使用WebClient。我必须在项目中使用Spring MVC,但感兴趣的是我是否可以使用WebClient来执行同时调用。有人可以建议如何使用WebClient正确完成此操作吗?

答案

假设一个WebClient包装器(如在reference doc中):

@Service
public class MyService {

    private final WebClient webClient;

    // the reference doc seems incorrect saying "public MyBean(" :)
    public MyService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://example.org").build();
    }

    public Mono<Details> someRestCall(String name) {
        return this.webClient.get().url("/{name}/details", name)
                        .retrieve().bodyToMono(Details.class);
    }

}

...,您可以通过以下方式异步调用它:

// ... 
  @Autowired
  MyService myService
  // ...

   Mono<Details> foo = myService.someRestCall("foo");
   Mono<Details> bar = myService.someRestCall("bar");
   Mono<Details> baz = myService.someRestCall("baz");

   // ..and use the results (thx to: [2] & [3]!):

   // Subscribes sequentially:

   // System.out.println("=== Flux.concat(foo, bar, baz) ===");
   // Flux.concat(foo, bar, baz).subscribe(System.out::print);

   // System.out.println("\n=== combine the value of foo then bar then baz ===");
   // foo.concatWith(bar).concatWith(baz).subscribe(System.out::print);

   // ----------------------------------------------------------------------
   // Subscribe eagerly (& simultaneously):
   System.out.println("\n=== Flux.merge(foo, bar, baz) ===");
   Flux.merge(foo, bar, baz).subscribe(System.out::print);

[2] [3]

谢谢,欢迎和亲切的问候,

另一答案

其他方式:

public Mono<Boolean> areVersionsOK(){
        final Mono<Boolean> isPCFVersionOK = getPCFInfo2();
        final Mono<Boolean> isBlueMixVersionOK = getBluemixInfo2();

        return isPCFVersionOK.mergeWith(isBlueMixVersionOK)
            .filter(aBoolean -> {
                return aBoolean;
            })
            .collectList().map(booleans -> {
                return booleans.size() == 2;
        });

    }

以上是关于如何使用Spring WebClient同时进行多个调用?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Spring5 WebClient 进行异步调用

Spring Boot Webclient - 等待多呼叫的结束响应

Spring WebClient 使用简介

Spring WebClient 使用简介

Spring WebClient 使用简介

Spring Boot WebClient OAuth - 同时命中多个请求时超时