How to use Spring WebClient to make multiple calls simultaneously?

前端 未结 4 2125
囚心锁ツ
囚心锁ツ 2021-01-01 22:30

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

I know this can be achieved using AsyncRestTemplate as it is mentioned here

4条回答
  •  爱一瞬间的悲伤
    2021-01-01 23:19

    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
    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
    foo = myService.someRestCall("foo"); Mono
    bar = myService.someRestCall("bar"); Mono
    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]

    Thanks, Welcome & Kind Regards,

提交回复
热议问题