使用WebClient结合Flux实现并行调用多个互不相关的http请求,并使结果按照调用顺序返回

使用WebClient结合Flux实现并行调用多个互不相关的http请求,并使结果按照调用顺序返回

java 复制代码
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Flux;

import java.util.List;

@Service
public class WebClientService {

    private final WebClient webClient;

    public WebClientService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://example.com").build();
    }

    public Mono<List<String>> makeDynamicRequests(List<String> endpoints) {
        // 发起 HTTP 请求并收集结果到 List
        return Flux.fromIterable(endpoints)
                .flatMap(endpoint -> webClient.get().uri(endpoint).retrieve().bodyToMono(String.class))
                .collectList(); // 收集结果到 List 中,保持顺序不乱
    }
}
相关推荐
架构师沉默14 小时前
别又牛逼了!AI 写 Java 代码真的行吗?
java·后端·架构
后端AI实验室18 小时前
我把一个生产Bug的排查过程,交给AI处理——20分钟后我关掉了它
java·ai
凉年技术20 小时前
Java 实现企业微信扫码登录
java·企业微信
狂奔小菜鸡21 小时前
Day41 | Java中的锁分类
java·后端·java ee
hooknum21 小时前
学习记录:基于JWT简单实现登录认证功能-demo
java
程序员Terry1 天前
同事被深拷贝坑了3小时,我教他原型模式的正确打开方式
java·设计模式
NE_STOP1 天前
MyBatis-缓存与注解式开发
java
码路飞1 天前
不装 OpenClaw,我用 30 行 Python 搞了个 QQ AI 机器人
java
Re_zero1 天前
以为用了 try-with-resources 就稳了?这三个底层漏洞让TCP双向通讯直接卡死
java·后端
SimonKing1 天前
Fiddler抓包完全指南:从安装配置到抓包,一文讲透
java·后端·程序员