使用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 中,保持顺序不乱
    }
}
相关推荐
GGGGGGGGGGGGGG.37 分钟前
使用dockerfile创建镜像
java·开发语言
兮动人2 小时前
SpringBoot加载配置文件的优先级
java·spring boot·后端·springboot加载配置
我爱Jack2 小时前
HttpServletRequest 和 HttpServletResponse 区别和作用
java·spring·mvc
yyueshen2 小时前
volatile 在 JVM 层面的实现机制
java·jvm
慕容魏2 小时前
入门到入土,Java学习 day16(算法1)
java·学习·算法
认真的小羽❅2 小时前
动态规划详解(二):从暴力递归到动态规划的完整优化之路
java·算法·动态规划
m0_748254662 小时前
Spring Boot 热部署
java·spring boot·后端
mango02192 小时前
SpringMVC
java
Seven972 小时前
SpringCloud带你走进微服务的世界
java·后端·spring cloud
Vacant Seat3 小时前
图论-实现Trie(前缀树)
java·开发语言·数据结构·图论