Search code examples
springspring-bootspring-webfluxasyncresttemplate

How to use Spring WebClient to make multiple calls simultaneously?


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 How to use AsyncRestTemplate to make multiple calls simultaneously?

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?


Solution

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

    Thanks, Welcome & Kind Regards,