java - 如何并行调用多个http请求(具有重试功能)并等待所有请求完成?

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

现在我的代码如下所示:

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

我如何才能等待所有回复都被接受的那一刻?

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

我怎样才能实现它?

最佳答案

我建议使用 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
}

关于java - 如何并行调用多个http请求(具有重试功能)并等待所有请求完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913196/

相关文章:

java - spring-boot 多线程聚合,反之亦然

spring-boot - Spring Boot 2、LiquiGraph 和 Actuator 运行状况端点的 503 错误 - org.springframework.jdbc.UncategorizedSQLException

java - NPAPI 的退役和数字签名的 future

java - 最佳数据库迁移方法?

java - 为什么要 "Make autowired dependencies explicit"?

java - lambda 中的控制反转

java - Spring Data Jpa 无需 @Query 即可连接多个表

java - 如何使用 Apache POI API 将图像添加到 pptx 中添加的图像占位符?

java - 我可以在 Java 中构建持续交付的任何东西吗?

java - Spring mvc 4 hello world 示例抛出 javax.servlet.ServletException : Failed to instantiate WebApplicationInitializer class