使用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 中,保持顺序不乱
}
}