简体   繁体   中英

How to make concurrent WebClient calls in a blocking Spring MVC app?

I'm trying to make parallel rest api calls to 5 different backend systems. Each rest api has different endpoints and different response types. I tried to accomplish this by using Webclient. I'm not able to figure out how to "block" the Mono's emitted by each api call at the same time.

Here is my sample code.

Mono<ClientResponse> userDetails = getUserDetails().subscribeOn(Schedulers.parallel());
Mono<ClientResponse> userAccountDetails = getUserAccountDetails().subscribeOn(Schedulers.parallel());

//getUserDetails and getUserAccountDetails does an exchange() and not retrieve() as i need access to the headers.

Tuple2<ClientResponse, ClientResponse> tuple = Mono.zip(userDetails, userAccountDetails).block();

tuple.getT1().bodyToMono(String.class).block()
tuple.getT2().bodyToMono(String.class).block()

The problem with this approach is even if I zipped the ClientResponses, I still have to invoke a block for each item.

You can just simply move the bodyToMono method call to the first and second line:

Mono<String> userDetails = getUserDetails().flatMap(r -> r.bodyToMono(String.class));
Mono<String> userAccountDetails = getUserAccountDetails().flatMap(r -> r.bodyToMono(String.class));

Tuple2<String, String> tuple = Mono.zip(userDetails, userAccountDetails).block();

String userDetailsResponse = tuple.getT1();
String userAccountDetailsResponse = tuple.getT2();

Also, note that I removed the subscribeOn(Schedulers.parallel()) operator. As you use WebClient under the hood explicit scheduling is not necessary to achieve concurrency, you get that out of the box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM