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

How to use Spring WebClient to make multiple calls simultaneously?

我想同时执行 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;

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

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

另一种方式:

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

    }

您可以使用简单的 RestTemplateExecutorService:

同时进行 HTTP 调用
RestTemplate restTemplate = new RestTemplate();
ExecutorService executorService = Executors.newCachedThreadPool();

Future<String> firstCallFuture = executorService.submit(() -> restTemplate.getForObject("http://first-call-example.com", String.class));
Future<String> secondCallFuture = executorService.submit(() -> restTemplate.getForObject("http://second-call-example.com", String.class));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

executorService.shutdown();

或者

Future<String> firstCallFuture = CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://first-call-example.com", String.class));
Future<String> secondCallFuture = CompletableFuture.supplyAsync(() -> restTemplate.getForObject("http://second-call-example.com", String.class));

String firstResponse = firstCallFuture.get();
String secondResponse = secondCallFuture.get();

您可以使用 Spring 反应式客户端 WebClient 发送并行请求。 在这个例子中,

public Mono<UserInfo> getUserInfo(User user) {
        Mono<UserInfo> userInfoMono = getUserInfo(user.getId());
        Mono<OrgInfo> organizationInfoMono = getOrgInfo(user.getOrgId());

        return Mono.zip(userInfoMono, organizationInfoMono).map(tuple -> {
            UserInfo userInfo = tuple.getT1();
            userInfo.setOrganization(tuple.getT2());
            return userInfo;
        });
    }

这里:

  • getUserInfo 进行 HTTP 调用以从另一服务获取用户信息,并且 returns Mono
  • getOrgInfo 方法进行 HTTP 调用以从另一个服务获取组织信息并且 returns Mono
  • Mono.zip() 等待所有单声道的所有结果并合并到一个新的单声道和 returns 它。

然后,调用getOrgUserInfo().block()得到最终结果。