使用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 中,保持顺序不乱
    }
}
相关推荐
真恋寄语枫秋2 小时前
【Java零基础入门23】Java线程池深度详解:核心参数、拒绝策略、四种创建方式
java
生活爱好者!2 小时前
用NAS进行漫画创作!一键部署Open WebUI
java·服务器·开发语言·安全·docker
Maddie_Mo2 小时前
Pi Agent Web 使用教程:把本地 Pi Coding Agent 搬进浏览器
android·java·前端·人工智能·ai
小马爱打代码2 小时前
Spring源码 第十二篇:Spring 全套核心原理 - 完结终章
java·后端·spring
AllData公司负责人2 小时前
亲测丝滑,体验跃迁|AllData通过集成开源项目RustFS,多模态数据存储新范式
java·大数据·数据库·算法·数据分析·rustfs
西安邮电大学3 小时前
2026华为OD机考真题附答案-准备生日礼物
java·后端
超梦dasgg3 小时前
Java 生产环境 RocketMQ 架构与部署指南
java·rocketmq·java-rocketmq
cheems95273 小时前
JWT令牌是如何实现登录认证的
java
happyprince3 小时前
10-Hugging Face Transformers 量化系统深度分析
java·前端·数据库