重試機制(一):Guava Retry

項目中經(jīng)常會遇到需要重試的場景,例如讀取數(shù)據(jù)庫,調(diào)用遠程api等??梢宰约簛韺崿F(xiàn)重試策略,但是不用重復(fù)造輪子,有很多設(shè)計好了的重試工具,例如guava包的retry,spring的retryable注解等。本文來了解一下guava retry的使用。

1. 使用Guava Retry

1.1 引入依賴

        <dependency>
            <groupId>com.github.rholder</groupId>
            <artifactId>guava-retrying</artifactId>
            <version>2.0.0</version>
        </dependency>

1.2 構(gòu)建retryer

    private static Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
            .retryIfException()
            .withStopStrategy(StopStrategies.stopAfterAttempt(3))
            .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
            .build();

1.3 主邏輯放在callable里,傳給retryer進行調(diào)用

    public int mockQueryDB() {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return doQuery();
            }
        };

        int result;
        try {
            result = retryer.call(callable);
        } catch (Exception e) {
            result = -1;
        }
        return result;
    }

doQuery里模擬了隨機報錯的場景:

    private int doQuery() {
        Random r = new Random(System.currentTimeMillis());
        int num = r.nextInt(5);
        System.out.println("query result " + num);

        if (num == 0) {
            return 0;
        } else if (num == 1) {
            System.out.println("DBException");
            throw new DBException("DBException");
        } else if (num == 2) {
            System.out.println("IllegalArgumentException");
            throw new IllegalArgumentException("IllegalArgumentException");
        } else if (num == 3) {
            System.out.println("NullPointerException");
            throw new NullPointerException("NullPointerException");
        } else {
            System.out.println("IndexOutOfBoundsException");
            throw new IndexOutOfBoundsException("IndexOutOfBoundsException");
        }
    }

1.4 執(zhí)行
根據(jù)配置,當發(fā)生異常時,會重試,最多執(zhí)行3次。每次嘗試中間會等待3秒。
如果執(zhí)行3次,仍然報錯,那么retryer.call會報RetryException:

com.github.rholder.retry.RetryException: Retrying failed to complete successfully after 3 attempts.

2. retryIfException

guava retry支持多種條件下重試,來具體看看。

2.1 retryIfException()
這個就是在任何異常發(fā)生時,都會進行重試。上面的例子中已經(jīng)用到。

2.2 retryIfRuntimeException()
這個是指,只有runtime exception發(fā)生時,才會進行重試。

2.3 retryIfExceptionOfType
發(fā)生某種指定異常時,才重試。例如

.retryIfExceptionOfType(DBException.class)

2.4 retryIfException(@Nonnull Predicate<Throwable> exceptionPredicate)
傳入一個條件,滿足條件,就會觸發(fā)重試。

.retryIfException(e -> e.getMessage().contains("NullPointerException"))

2.5 多個retryIfException串起來時,滿足其中之一,就會觸發(fā)重試。

.retryIfExceptionOfType(DBException.class)
.retryIfException(e -> e.getMessage().contains("NullPointerException"))

3. retryIfResult

當執(zhí)行沒有發(fā)生異常,但是當返回某些結(jié)果時,依然想進行重試,那么就可以使用retryIfResult。

.retryIfResult(e -> e.intValue() == 0)

此例中,當返回值為0時,會觸發(fā)重試。

4. StopStrategies

4.1 StopStrategies.stopAfterAttempt

.withStopStrategy(StopStrategies.stopAfterAttempt(3))

4.2 StopStrategies.stopAfterDelay
指定時間,多次嘗試直到指定時間。

.withStopStrategy(StopStrategies.stopAfterDelay(10, TimeUnit.SECONDS))

4.3 StopStrategies.neverStop
一直重試,不會停止。如果不指定StopStrategies,似乎也是一樣的效果。

.withStopStrategy(StopStrategies.neverStop())

4.4 同時設(shè)置多個StopStrategies?
不能設(shè)置多個,會報錯:

java.lang.IllegalStateException: a stop strategy has already been set 
com.github.rholder.retry.StopStrategies$StopAfterAttemptStrategy@21c7208d

5. WaitStrategies

5.1 WaitStrategies.fixedWait
固定等待時間

.withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS))

5.2 WaitStrategies.exponentialWait
指數(shù)等待時間。

// 第一二次之間等待 2 ms,接下來等 2*2 ms, 2*2*2 ms, ...
.withWaitStrategy(WaitStrategies.exponentialWait())

//指數(shù)等待時間,最多10s。超過10s,也只等待10s。
.withWaitStrategy(WaitStrategies.exponentialWait(10, TimeUnit.SECONDS))

// 等待時間乘以 5的系數(shù)。指數(shù)級增長,最多不超過10s.
.withWaitStrategy(WaitStrategies.exponentialWait(5, 10, TimeUnit.SECONDS))

5.3 WaitStrategies.fibonacciWait
以斐波那契數(shù)列的方式增長。參數(shù)含義與exponentialWait類似。

.withWaitStrategy(WaitStrategies.fibonacciWait())
.withWaitStrategy(WaitStrategies.fibonacciWait(10, TimeUnit.SECONDS))
.withWaitStrategy(WaitStrategies.fibonacciWait(5, 10, TimeUnit.SECONDS))

5.4 WaitStrategies.exceptionWait
對于不同的異常類型,定義不同的等待時間策略。

.withWaitStrategy(WaitStrategies.exceptionWait(DBException.class, x -> 50l))

5.5 WaitStrategies.randomWait
等待隨機的時間。

//等待時間為 0 到3秒 之間的隨機時間
.withWaitStrategy(WaitStrategies.randomWait(3, TimeUnit.SECONDS))

//等待時間為 1秒到3秒之間的隨機時間
.withWaitStrategy(WaitStrategies.randomWait(1, TimeUnit.SECONDS, 3, TimeUnit.SECONDS))

5.6 WaitStrategies.incrementingWait
等待時間遞增。例如,第一二次之間等待1秒,接下來每次增加3秒。

.withWaitStrategy(WaitStrategies.incrementingWait(1, TimeUnit.SECONDS, 3, TimeUnit.SECONDS))

5.7 WaitStrategies.noWait
不等待,直接重試。

.withWaitStrategy(WaitStrategies.noWait())

5.8 WaitStrategies.join
WaitStrategies.join可以將多種等待策略組合起來,等待時間為多個策略的時間和。
例如,join了exponentialWait和fixedWait:

.withWaitStrategy(WaitStrategies.join(WaitStrategies.exponentialWait(100, 5, TimeUnit.SECONDS), 
    WaitStrategies.fixedWait(1, TimeUnit.SECONDS)))

輸出為:

2022-05-03 22:01:08.946  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 0
IndexOutOfBoundsException
2022-05-03 22:01:10.148  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 4
IndexOutOfBoundsException
2022-05-03 22:01:11.554  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 3
NullPointerException
2022-05-03 22:01:13.359  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 4
IndexOutOfBoundsException
2022-05-03 22:01:15.965  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 0
IndexOutOfBoundsException
2022-05-03 22:01:20.166  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 3
NullPointerException
2022-05-03 22:01:26.171  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 3
NullPointerException
2022-05-03 22:01:32.175  INFO 7228 --- [           main] com.springbootdemo.util.GuavaRetryUtil   : doQuery
query result 4
IndexOutOfBoundsException

等待時間間隔為:
1s + 200ms
1s + 400ms
1s + 800ms
1s + 1600ms
......

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容