使用WebClient发出多个请求

时间:2019-05-01 06:01:47

标签: java spring spring-boot spring-webflux project-reactor

所以我的目标是使用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;
}

基本上,我的目标是合并每个提要中的所有项目以创建一个统一的提要。但是,我不确定在调用Flux :: merge之后该怎么做。任何建议,将不胜感激。

1 个答案:

答案 0 :(得分: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代替。