【问题标题】:How to call several http requests in parallel(with retry functionality) and await when all of them are finish?如何并行调用多个http请求(具有重试功能)并等待所有请求完成?
【发布时间】:2020-03-13 17:48:27
【问题描述】:

目前我的代码如下所示:

   List<Mono<ResponseEntity<String>>> response = queue.stream()
            .map(req-> webClient
                    .post()
                    .bodyValue(req)
                    .retrieve()
                    .toEntity(String.class)
            )
            .collect(Collectors.toList());

我怎么能等待所有回复都被接受的那一刻?

如果某些请求失败,我只想重试它们。

我怎样才能实现它?

【问题讨论】:

  • 我猜你想要自动重试?或者你想明确地重试它们?
  • @Haris Osmanagić 我更喜欢自动重试。 WebClient 开箱即用地支持单个请求
  • 您绝对可以使用 Executor,并将您的所有请求作为任务提交。如果您可以使用 WebClient 轻松重试单个请求,那么等待所有请求完成非常容易。

标签: java spring spring-boot spring-webflux spring-webclient


【解决方案1】:

我建议使用MonoFlux 的功能,而不是使用另一个答案建议的ExecutorService,这提供了一个更惯用的解决方案:

Mono<List<String>> response = Flux.fromIterable(queue)
                                  .flatMap(this::callHttp)
                                  .collectList();

private Mono<String> callHttp(String req)
{
    return webClient
            .post()
            .syncBody(req)
            .retrieve()
            .bodyToMono(String.class)
            .retry(3); // retries failed requests at most 3 times
}

【讨论】:

    【解决方案2】:

    最简单且直截了当的解决方案是编写一个代码,发送带有重试的单个请求,并且仅在成功完成或超出最大重试限制后返回。之后将该代码包装为 Runnable 的实现并使用 ExecutorService 提交所有这些。将 Futures 收集到一个集合中并检查它们何时全部完成。

    【讨论】:

    • 当你有 Project Reactor 可供使用时,我认为使用 ExecutorService 和 Future 没有意义。
    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 2020-05-26
    相关资源
    最近更新 更多