Failsafe RetryPolicy - 从 supplyAsync 抛出异常

Failsafe RetryPolicy - throw exception from supplyAsync

我正在实施重试政策。基本上我想做的是在单独的线程上重试 POST 请求。我正在使用 jhalterman 的 failsafe (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' 中抛出异常,以便由重试策略处理? 谢谢。 谢谢

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));