使用WebClient发出多个请求

问题描述 投票:0回答:1

所以我的目标是使用WebClient发出多个并发请求,等待它们全部完成,然后合并结果。这是我到目前为止:

...

Flux<ServerResponse> feedResponses = request
        .bodyToMono(AddFeedRequestDto.class)
        .map(AddFeedRequestDto::getFeeds) // Returns a list of RSS feed URLs
        .map(this::getServerResponsesFromUrls) // Returns a list of Mono<Feed>
        .map(Flux::merge) // Wait til all requests are completed
        // Not sure where to go from here

...

/** Related methods: **/

private List<Mono<Feed>> getServerResponsesFromUrls(List<String> feedUrls) {
    List<Mono<Feed>> feedResponses = new ArrayList<>();
    feedUrls.forEach(feedUrl -> feedResponses.add(getFeedResponse(feedUrl)));
    return feedResponses;
}

public Mono<Feed> getFeedResponse(final String url) {
    return webClient
            .get()
            .uri(url)
            .retrieve()
            .bodyToMono(String.class) // Ideally, we should be able to use bodyToMono(FeedDto.class)
            .map(this::convertResponseToFeedDto)
            .map(feedMapper::convertFeedDtoToFeed);
}

/** Feed.java **/
@Getter
@Setter
public class Feed {
    List<Item> items;
}

基本上我的目标是组合每个Feed中的所有项目来创建一个统一的Feed。但是,在调用Flux :: merge之后,我不太清楚要做什么。任何建议,将不胜感激。

java spring spring-boot spring-webflux project-reactor
1个回答
2
投票

使用.flatMap而不是.map / Flux.merge,如下所示:

Mono<Feed> unifiedFeedMono = request
        .bodyToMono(AddFeedRequestDto.class)  // Mono<AddFeedRequestDto>
        .map(AddFeedRequestDto::getFeeds)     // Mono<List<String>> feedUrls
        .flatMapMany(Flux::fromIterable)      // Flux<String> feedUrls
        .flatMap(this::getFeedResponse)       // Flux<Feed>
        .map(Feed::getItems)                  // Flux<List<Item>>
        .flatMap(Flux::fromIterable)          // Flux<Item>
        .collectList()                        // Mono<List<Item>>
        .map(Feed::new);                      // Mono<Feed>

请注意,.flatMap是一个异步操作,将并行执行请求。如果要限制并发,有一个重载版本需要concurrency参数。

使用.flatMap无法保证排序,并且生成的项目可能是交错的。如果您想要更多订购保证,请替换.concatMap.flatMapSequential

© www.soinside.com 2019 - 2024. All rights reserved.