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次(这是默认值(
可能您在Supplier中抛出异常,而不是在Supplier.get((代码返回的future中。我尝试了以下代码:
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
正如预期的那样!