首页 > 解决方案 > 从 Springboot + Webflux 中发出并行请求

问题描述

我正在使用带有 webflux 堆栈的 Springboot 2。

在应用程序中,我希望向下游服务并行发出多个 HTTP 请求,以减少返回客户端的总体响应时间。如果不玩线程,这可能吗?

我目前正在使用org.springframework.web.reactive.function.client.WebClient但对支持此功能的其他客户开放;甚至是 RXJava。

标签: reactive-programming

解决方案


我设法通过以下方式实现了它。这是一个天真的例子,但是 async/http 请求是在downstream.request1()和中发出的downstream.request2()。如果是一种更优雅的方式来实现这一点,我会感兴趣。

@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);
}

推荐阅读