簡體   English   中英

Resilience4j 使用 CompletionStage 重試

[英]Resilience4j retry with CompletionStage

    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 次(這是默認值)

可能您在供應商中拋出異常,而不是在供應商.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

正如預期的那樣!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM