n00b
n00b

Reputation: 6360

Making parallel requests from within Springboot + Webflux

I'm playing around with Springboot 2 with the webflux stack.

Within the application I'm looking to make multiple HTTP requests in parallel to downstream services to reduce the overall response time back to the client. Is this possible without playing around with threads?

I'm currently using org.springframework.web.reactive.function.client.WebClient but open to other clients that would support this; or even RXJava.

Upvotes: 0

Views: 2512

Answers (1)

n00b
n00b

Reputation: 6360

I managed to achieve it by something like below. It's a naive example but the async/http requests are made in downstream.request1() and downstream.request2(). If is a more elegant way to achieve this I'd be interested.

@GetMapping("/sample")
public Mono<String> getMultipleRequests() {
    Mono<String> monoResponse1 = downstream.request1();
    Mono<String> monoResponse2 = downstream.request2();

    return Mono.zip(monoResponse1, monoResponse2)
        .flatMap(a -> myTransform(a));
}

private Mono<String> myTransform(Tuple2<String, String> tuple) {
    String t1 = tuple.getT1();
    String t2 = tuple.getT2();
    return Mono.just(t1 + t2);
}

Upvotes: 2

Related Questions