Java

重试机制(一):Guava Retry

2022-05-03  本文已影响0人  overflowedstack

项目中经常会遇到需要重试的场景,例如读取数据库,调用远程api等。可以自己来实现重试策略,但是不用重复造轮子,有很多设计好了的重试工具,例如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 构建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进行调用

    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 执行
根据配置,当发生异常时,会重试,最多执行3次。每次尝试中间会等待3秒。
如果执行3次,仍然报错,那么retryer.call会报RetryException:

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

2. retryIfException

guava retry支持多种条件下重试,来具体看看。

2.1 retryIfException()
这个就是在任何异常发生时,都会进行重试。上面的例子中已经用到。

2.2 retryIfRuntimeException()
这个是指,只有runtime exception发生时,才会进行重试。

2.3 retryIfExceptionOfType
发生某种指定异常时,才重试。例如

.retryIfExceptionOfType(DBException.class)

2.4 retryIfException(@Nonnull Predicate<Throwable> exceptionPredicate)
传入一个条件,满足条件,就会触发重试。

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

2.5 多个retryIfException串起来时,满足其中之一,就会触发重试。

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

3. retryIfResult

当执行没有发生异常,但是当返回某些结果时,依然想进行重试,那么就可以使用retryIfResult。

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

此例中,当返回值为0时,会触发重试。

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 同时设置多个StopStrategies?
不能设置多个,会报错:

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
指数等待时间。

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

//指数等待时间,最多10s。超过10s,也只等待10s。
.withWaitStrategy(WaitStrategies.exponentialWait(10, TimeUnit.SECONDS))

// 等待时间乘以 5的系数。指数级增长,最多不超过10s.
.withWaitStrategy(WaitStrategies.exponentialWait(5, 10, TimeUnit.SECONDS))

5.3 WaitStrategies.fibonacciWait
以斐波那契数列的方式增长。参数含义与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
......

上一篇下一篇

猜你喜欢

热点阅读