Home > Mobile >  Calling Multiple apis synchronously, spring boot webflux
Calling Multiple apis synchronously, spring boot webflux

Time:02-18

In my project we are using spring boot webflux, and I have this scenario where i have to call multiple api's from within a particular microservice synchronously. e.g.

for(String api:apiNames){
   //call api's
   }

As per my understanding, webClient works asynchronously, until and unless someone subscribe to it it wont release the response.

in my current scenario i have to make use of webclient and I have to call each api only after successfull execution of previous api.

Note:- api response can be anything success/failure

Please help me in implementing this synchronous call

CodePudding user response:

You can use the #block() method to make it synchronous. Example on a mono (https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Mono.html#block--)

For example on the (asynchronous) webflux webclient:

return webClient.get()
                .uri(uri)
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(String.class)
                .block();

The above example will wait with executing any next line of code untill it has received a response. After which you can just make another call to another api in the same way.

Edit: As pointed out in the comments I would like to add a warning that using #block() is not efficient and you should try and chain more reactive calls and try to avoid making your application non reactive.

A nice post with more details can be found here: https://stackoverflow.com/a/57365926/1326867

CodePudding user response:

Although, the question uses the word "synchronously", the description rather seems to suggest that sequentiality is what is needed, meaning executing each request one after the other.

If that's the requirement, it can be implemented the following way with Reactor:

Flux.fromIterable(apiNames)
  .concatMap(apiName -> webClient...) // concatMap ensures sequential execution

However, if the application is a blocking Spring application, then Nick Hol's answer is also a correct one.

  • Related