使用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 中,保持顺序不乱
    }
}
相关推荐
用户29869853014几秒前
Java 进阶:基于模板生成 Word 文档的实践思路
java·后端
涛声依旧-底层原理研究所2 分钟前
响应式编程:map与flatMap实战解析
java
无心水44 分钟前
【OpenClaw:赚钱】案例19、内容产量5倍、广告收入翻4倍:播客转多平台内容矩阵全自动化实战(OpenAI Whisper + Claude)
java·人工智能·python·ai编程·openclaw·养龙虾·java.time
云烟成雨TD1 小时前
Spring AI 1.x 系列【42】MCP 服务端 Spring Boot 启动器
java·人工智能·spring
云烟成雨TD1 小时前
Spring AI 1.x 系列【38】模型上下文协议(MCP)
java·人工智能·spring
Alson_Code1 小时前
Spring AI-1.1.0
java·人工智能·后端·spring·ai编程
ANnianStriver1 小时前
PetLumina 08 — 通知系统与搜索功能修复(广播机制 + 已读状态 + 参数对齐)
java·ai·ai编程·广播机制
ggaofeng1 小时前
试用zeroclaw
java·开发语言
就叫_这个吧1 小时前
servlet整合tomcat项目启动报错解决,org.apache.tomcat.util.descriptor.web.WebXml.setVersion
java·servlet·tomcat·apache
Wenzar_1 小时前
用 JAX 构建可微分光子神经网络仿真器
java·人工智能·深度学习·神经网络