使用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 中,保持顺序不乱
    }
}
相关推荐
RainbowSea9 小时前
12. LangChain4j + 向量数据库操作详细说明
java·langchain·ai编程
RainbowSea9 小时前
11. LangChain4j + Tools(Function Calling)的使用详细说明
java·langchain·ai编程
考虑考虑13 小时前
Jpa使用union all
java·spring boot·后端
用户37215742613513 小时前
Java 实现 Excel 与 TXT 文本高效互转
java
浮游本尊14 小时前
Java学习第22天 - 云原生与容器化
java
渣哥16 小时前
原来 Java 里线程安全集合有这么多种
java
间彧16 小时前
Spring Boot集成Spring Security完整指南
java
间彧17 小时前
Spring Secutiy基本原理及工作流程
java
Java水解18 小时前
JAVA经典面试题附答案(持续更新版)
java·后端·面试
洛小豆20 小时前
在Java中,Integer.parseInt和Integer.valueOf有什么区别
java·后端·面试