使用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 中,保持顺序不乱
    }
}
相关推荐
J2虾虾3 分钟前
Android支持Java语言的标准
android·java·开发语言
Oo_行者_oO12 分钟前
Spring Schedule + ShedLock + RabbitMQ 生产级落地方案 - 云楼(中国)
java·后端
AI人工智能+电脑小能手16 分钟前
【大白话说Java面试题 第113题】【并发篇】第13题:说一下乐观锁的优点和缺点?
java·开发语言·面试
Mahir0819 分钟前
HashMap 底层原理深度解密:从数据结构到 JDK1.7/1.8 演进全解
java·后端·面试·hashmap
小马爱打代码22 分钟前
Spring Boot 自动装配流程
java·spring boot·后端
我登哥MVP28 分钟前
SpringCloud 核心组件解析:分布式配置管理
java·spring boot·分布式·spring·spring cloud·java-ee·maven
lihao lihao29 分钟前
linux线程
java·开发语言·jvm
满怀冰雪30 分钟前
第13篇-栈算法入门-括号匹配-表达式与单调栈基础
java·算法
我是一颗柠檬34 分钟前
【Java项目技术亮点】Redis Lua脚本原子化操作:高并发场景下的终极武器
java·redis·lua