使用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 中,保持顺序不乱
    }
}
相关推荐
卷到起飞的数分13 小时前
JVM探究
java·服务器·jvm
Geek攻城猫13 小时前
Java生产环境问题排查实战指南
java·jvm
OtIo TALL21 小时前
redis7 for windows的安装教程
java
uNke DEPH21 小时前
Spring Boot的项目结构
java·spring boot·后端
xixingzhe21 天前
idea启动vue项目
java·vue.js·intellij-idea
wzl202612131 天前
企业微信定时群发技术实现与实操指南(原生接口+工具落地)
java·运维·前端·企业微信
凌波粒1 天前
Java 8 “新”特性详解:Lambda、函数式接口、Stream、Optional 与方法引用
java·开发语言·idea
曹牧1 天前
Eclipse:悬停提示(Hover)
java·ide·eclipse
oyzz1201 天前
Spring EL 表达式的简单介绍和使用
java·后端·spring
iNgs IMAC1 天前
Redis之Redis事务
java·数据库·redis