【问题标题】:Resilience4j retry with CompletionStageResilience4j 使用 CompletionStage 重试
【发布时间】:2021-09-25 17:25:46
【问题描述】:
    private CompletionStage<org.asynchttpclient.Response> executeWithRetries(Request request) {
    RetryConfig retryConfig = RetryConfig.<org.asynchttpclient.Response>custom()
            .maxAttempts(5)
            .intervalFunction(IntervalFunction
                    .ofExponentialBackoff(TimeUnit.SECONDS.toMillis(2), 1.2))
            .build();
    Retry retry = Retry.of("proxy-retry" , retryConfig);
    Supplier<CompletionStage<org.asynchttpclient.Response>> retryableSupplier = Retry.decorateCompletionStage(
            retry , Executors.newScheduledThreadPool(10),  () -> executeCall(request));

    return retryableSupplier.get();
}

我正在使用这种方法,希望 executeCall 在抛出异常时至少重试 3 次。 executeCall(request) 方法返回一个 CompletionStage。

当我尝试对这段代码进行单元测试时,executeCall(request) 方法的调用次数只有一次(我在这个方法中抛出了一个异常)。

如何确保它至少重试 5 次(这是默认值)

【问题讨论】:

    标签: java resilience4j completion-stage resilience4j-retry


    【解决方案1】:

    您可能会在 Supplier 中抛出异常,而不是在 Supplier.get() 代码返回的未来中。我试过以下代码:

    import java.util.concurrent.*;
    import java.util.function.*;
    import io.github.resilience4j.retry.*;
    
    public class Main {
        private static final ScheduledExecutorService scheduledExecutorService =
                Executors.newScheduledThreadPool(10);
    
        public static void main(final String[] args) {
            RetryConfig retryConfig = RetryConfig.custom()
                    .maxAttempts(5)
                    .intervalFunction(
                            IntervalFunction.ofExponentialBackoff(10, 1.2))
                    .build();
    
            Retry retry = Retry.of("proxy-retry", retryConfig);
    
            Supplier<CompletionStage<String>> supplier =
                    () -> CompletableFuture.supplyAsync(() -> {
                        System.out.println("failing code");
                        throw new RuntimeException();
                    });
    
            retry.executeCompletionStage(scheduledExecutorService, supplier);
        }
    }
    

    输出是:

    failing code
    failing code
    failing code
    failing code
    failing code
    

    正如预期的那样!

    【讨论】:

      猜你喜欢
      • 2021-11-20
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 2021-02-07
      • 2021-05-09
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      相关资源
      最近更新 更多