【问题标题】:Failsafe RetryPolicy - throw exception from supplyAsyncFailsafe RetryPolicy - 从 supplyAsync 抛出异常
【发布时间】:2019-05-03 23:30:53
【问题描述】:

我正在实施重试策略。基本上我想要做的是在单独的线程上重试 POST 请求。我正在使用 jhalterman (https://github.com/jhalterman/failsafe#asynchronous-api-integration) 的故障保护,这是我的代码

Failsafe.with(retryPolicy).with(executor).future(() -> CompletableFuture.supplyAsync(() -> {
            try {
                CloseableHttpResponse response = client.execute(httpPost);
                httpPost.releaseConnection();
                client.close();
                return response;
            } catch (IOException e) {
                return null;
            }
        }).thenApplyAsync(response -> "Response: " + response)
          .thenAccept(System.out::println));

我不想在这里捕获 IOException。它由重试策略处理。目前不会发生重试,因为我在这里发现了异常。有没有办法从“supplyAsync”抛出异常,以便由重试策略处理? 谢谢。 谢谢

【问题讨论】:

    标签: java asynchronous completable-future retrypolicy java-failsafe


    【解决方案1】:

    CompletionStage API 提供了几种不同的方式来处理和处理未经检查的异常。但在你的情况下,你得到的是一个 Checked 异常,你不走运。您要么必须处理它,要么将其向外扔给您的来电者。如果您更喜欢后一种方法,这是一种方法。

    Failsafe.with(retryPolicy).with(executor).future(() -> CompletableFuture.supplyAsync(() -> {
                try {
                    // Remainder omitted
                    return response;
                } catch (IOException e) {
                    throw new CompletionException(e);
                }
            }).thenApplyAsync(response -> "Response: " + response)
              .thenAccept(System.out::println));
    

    【讨论】:

      猜你喜欢
      • 2013-05-24
      • 1970-01-01
      • 2011-07-17
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多