How to use Spring WebClient to make multiple calls sequentionaly?

1k views Asked by At

I read the topic How to use Spring WebClient to make multiple calls simultaneously? , but my case is a bit different. I'm calling 2 different external services using webclient, let's say from method Mono < Void > A() , followed by Mono < Void > B (). My goal is to extract data from A(), then pass it to B(). Is there correct way to avoid:

  • asynchronous call (which leads to Illegal arg exception, since B requesting args BEFORE A() complete);
  • blocking call, cause the system is reactive.

Is there are a standart way to achieve it?

2

There are 2 answers

2
Manish Bansal On

First scenario:

Mono<> a = getFromAByWebClient();

and you want to send this data to call service B via a post or put request,

here, since mono is one object and you want to send it through api in a post or method, so must have that data with you, here you should wait until data is not come from first service, else it will hit the api with blank data or will result an exception.

Second scenario:

Since B is dependent on A, why not to call A service inside B service and get data.

Since in Spring reactive everything is stream, so can do operation with one data until others are on their way, but that operations which will be performed should have data.

0
tarmogoyf On

Well, I was told how to refactor the code. The problem was fixed and for memorizing, here is the solution:

  • the original code returns

    Mono.fromRunnable(()->apply(param param));
    
  • method 'apply' subscribes on call of external resource:

      apply(param param) {
      service.callRemote(val x).subscribe();
    
      <---some bl --->
    
      };
    

So,it seems Like when first beanA.process() followed beanB.process(), reactive pipeline falls apart, and lambda from runnable() branches into separate thread.

What was changed: beanA and beanB methods apply return logic -

     Mono.just.flatMap(service.callRemote(val x)).then();

apply() has been removed, remote call wrapped into flatMap() and integrated into pipeline. Now it works as expected, sequentionally calling remote resource.