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

新手上路,请多包涵

我想同时执行 3 个调用,并在它们全部完成后处理结果。

我知道这可以使用 AsyncRestTemplate 来实现,正如这里提到的 如何使用 AsyncRestTemplate 同时进行多个调用?

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

原文由 ddzz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 920
1 个回答

假设一个 WebClient 包装器(如 参考文档):

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

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

原文由 xerx593 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题