0
    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 次(这是默认值)

4

1 回答 1

0

可能您在 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-07-19T09:50:08.113 回答