使用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 分钟前
力扣 968. 监控二叉树 —— 贪心 & 树形 DP 双解法递归 + 非递归全解(Java 实现)
java·算法·leetcode·贪心算法·动态规划·力扣·
quxuexi36 分钟前
网络通信安全与可靠传输:从加密到认证,从状态码到可靠传输
java·安全·web
hrhcode1 小时前
【java工程师快速上手go】二.Go进阶特性
java·golang·go
小碗羊肉3 小时前
【从零开始学Java | 第三十一篇下】Stream流
java·开发语言
❀͜͡傀儡师3 小时前
Spring AI Alibaba vs. AgentScope:两个阿里AI框架,如何选择?
java·人工智能·spring
aq55356003 小时前
Laravel10.x重磅升级,新特性一览
android·java·开发语言
一 乐4 小时前
酒店预订|基于springboot + vue酒店预订系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·酒店预订系统
Moe4884 小时前
Spring AI Advisors:从链式增强到递归顾问
java·后端
敖正炀4 小时前
ReentrantReadWriteLock、ReentrantLock、synchronized 对比
java
cike_y4 小时前
Java反序列化漏洞-Shiro721流程分析
java·反序列化·shiro框架