使用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 中,保持顺序不乱
    }
}
相关推荐
用户35218024547511 小时前
当 Prompt 学会"热更新":Spring Boot × Nacos3 AI 实战
java·spring boot·ai编程
东坡白菜14 小时前
破局全栈:一个前端开发的Java入门实战记录(1)
java·全栈
唐青枫14 小时前
Java Tomcat 实战指南:从 Servlet 容器到 Spring Boot 部署
java
wsaaaqqq14 小时前
roudan:自由选择实体、灵活操作数据、快速写入数据库的 Java 框架
java
plainGeekDev18 小时前
null 判断 → Kotlin 可空类型
android·java·kotlin
糖拌西瓜皮18 小时前
Java开发者视角:深入理解Node.js异步编程模型
java·后端·node.js
plainGeekDev18 小时前
getter/setter → Kotlin 属性
android·java·kotlin
一线大码18 小时前
Smart-Doc 的简单使用
java·后端·restful
MacroZheng20 小时前
Claude Code官方桌面端正式发布,夯爆了!
java·人工智能·后端