使用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 中,保持顺序不乱
    }
}
相关推荐
無限進步D35 分钟前
Java 运行原理
java·开发语言·入门
難釋懷36 分钟前
安装Canal
java
是苏浙37 分钟前
JDK17新增特性
java·开发语言
阿里加多4 小时前
第 4 章:Go 线程模型——GMP 深度解析
java·开发语言·后端·golang
likerhood4 小时前
java中`==`和`.equals()`区别
java·开发语言·python
小小李程序员4 小时前
Langchain4j工具调用获取不到ThreadLocal
java·后端·ai
zs宝来了5 小时前
AQS详解
java·开发语言·jvm
lulu12165440787 小时前
Claude Code Harness架构技术深度解析:生产级AI Agent工程化实践
java·人工智能·python·ai编程
阿里加多7 小时前
第 1 章:Go 并发编程概述
java·开发语言·数据库·spring·golang