使用WebClient结合Flux实现并行调用多个互不相关的http请求,并使结果按照调用顺序返回
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) {return Flux.fromIterable(endpoints).flatMap(endpoint -> webClient.get().uri(endpoint).retrieve().bodyToMono(String.class)).collectList(); }
}