首页 文章

SpringBoot WebFlux - 制作并行WebClient请求

提问于
浏览
1

我正在尝试使用新的SpringBoot 2 Reactive WebClient类(它没有批处理 endpoints )对同一个休息服务进行并行(批量)调用 . 例如,我需要100个“注释”对象(使用ID 1 ... 100)并且我正在执行以下并行调用:

List<Mono<Comment>> monos = ids.stream()
            .map(id -> webClient.get()
                    .uri("/comments/{id}", id)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .bodyToMono(Comment.class))
            .collect(Collectors.toList());

    return Flux.merge(monos);

我是Spring WebFlux的新手,我不确定这是使用WebClient进行并行调用的正确方法

  • 有没有更好(更合适)的方法(即做一个Monos的Flux concat)?

  • 此外,当我这样做时,旧的弃用的AsyncRestTemplate我使用了
    ThreadPoolExecutor ...我应该使用类似的概念吗?
    WebClient? ......有没有与被动相似的东西?

问候

完整的源代码可以绑定在:https://github.com/fdlessard/SpringBootReactiveComment

1 回答

  • 1
    Flux.fromIterable(ids)
      .flatMap(id -> webClient.get()
        .uri("/comments/{id}", id)
        .accept(MediaType.APPLICATION_JSON)
        .retrieve()
        .bodyToMono(Comment.class))
      .subscribeOn(Schedulers.parallel());
    

相关问题