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

问题描述 投票:7回答:2

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

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

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

spring spring-boot spring-webflux asyncresttemplate
2个回答
6
投票

假设一个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]

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


0
投票

其他方式:

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

    }
© www.soinside.com 2019 - 2024. All rights reserved.