使用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 中,保持顺序不乱
    }
}
相关推荐
BillKu21 分钟前
Java解析前端传来的Unix时间戳
java·前端·unix
幼稚诠释青春22 分钟前
面试实例题
java·开发语言
cui_hao_nan33 分钟前
多轮对话实现
java·语言模型
饼干ovo35 分钟前
shell编程
java·git·github
华科云商xiao徐1 小时前
Java使用Jsoup库实现通用爬虫
java·爬虫
闲敲棋子落灯华1 小时前
java学习笔记(三)--java包的引入、访问控制、类的继承、super关键字、重载、重写、运算符、拆箱
java·后端
程序员岳焱1 小时前
Java 使用 Spring AI 的 10 个实用技巧
java·后端·程序员
Bug改不动了1 小时前
迁移达梦数据库过程中,如何快速识别需要改写的Mapper SQL方法
java·mybatis
crud1 小时前
Spring Boot 使用 @Async 实现异步操作:从入门到实战,一文讲透
java·spring boot