如何使用Spring WebClient同时进行多个调用? [英] How to use Spring WebClient to make multiple calls simultaneously?

查看:659
本文介绍了如何使用Spring WebClient同时进行多个调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时执行3个调用,并在完成所有结果后对其进行处理.

I want to execute 3 calls simultaneously and process the results once they're all done.

我知道这可以通过使用AsyncRestTemplate来实现,如此处

I know this can be achieved using AsyncRestTemplate as it is mentioned here How to use AsyncRestTemplate to make multiple calls simultaneously?

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

However, AsyncRestTemplate is deprecated in favor of WebClient. I have to use Spring MVC in the project but interested if I can use a WebClient just to execute simultaneous calls. Can someone advise how this should be done properly with WebClient?

推荐答案

假定一个WebClient包装器(例如

Assuming a WebClient wrapper (like in 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);
    }

}

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

..., you could invoke it asynchronously via:

// ... 
  @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]

谢谢,欢迎与amp;亲切的问候,

Thanks, Welcome & Kind Regards,

这篇关于如何使用Spring WebClient同时进行多个调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆