The guava-retrying module provides a general purpose method for retrying arbitrary Java code with specific stop, retry, and exception handling capabilities that are enhanced by Guava’s predicate matching.
maven依赖
1 | <dependency> |
使用说明
简单的demo
1 | Callable<Boolean> callable = new Callable<Boolean>() { |
首先重试的内容主体必须是一个Callable的实现,重试是根据其call方法的执行状态(异常、返回值)定制的重试策略来进行重试的。
比如上面的列子。重试者retryer由建造者RetryerBuilder创建的,RetryerBuilder提供了各种方法来定制重试策略。
根据返回是否是null来决定是否重试
1 | .retryIfResult(Predicates.<Boolean>isNull()) |
根据异常类型是否是IOException来决定是否重试
1 | .retryIfExceptionOfType(IOException.class) |
多个类型的时候还可以使用Predicate
1 | Retryer<Void> retryer1 = RetryerBuilder.<Void>newBuilder() |
根据异常是否是RuntimeException来决定是否重试
1 | .retryIfRuntimeException() |
设置重试的终止策略,尝试3次后终止
1 | .withStopStrategy(StopStrategies.stopAfterAttempt(3)) |
除了上述重试判断外判断重试的方式与策略还有很多,比如
重试判断
返回值匹配
1 | .retryIfResult(Predicates.containsPattern("_error$")) |
1 | .retryIfResult(Predicates.equalTo(2)) |
终止策略
常用的终止策略在com.github.rholder.retry.StopStrategies中。
尝试3次后终止
1 | .withStopStrategy(StopStrategies.stopAfterAttempt(3)) |
30s后终止
1 | .withStopStrategy(StopStrategies.stopAfterDelay(30,TimeUnit.SECONDS)) |
不终止
1 | .withStopStrategy(StopStrategies.neverStop()) |
等待策略
很多场景下并不是立即重试(环境影响,立即重试的失败率依旧很高),一般会等待一段时间后继续重试。
提供了等待策略,常用策略在com.github.rholder.retry.WaitStrategies中。
比如
等待固定时间
1 | .withWaitStrategy(WaitStrategies.fixedWait(5L, TimeUnit.SECONDS)) |
每次等待时间递增
1 | .withWaitStrategy(WaitStrategies.incrementingWait(3, TimeUnit.SECONDS,1,TimeUnit.SECONDS)) |
斐波那契式等待
1 | .withWaitStrategy(WaitStrategies.fibonacciWait()) |
重试监听
guava-retrying提供每次重试的监听机制,每次重试后会回调注册的监听者,按顺序依次执行。
监听者必须实现RetryListener.onRetry的方法。参数attempt是每次尝试的记录。
1 | public class MyRetryListener<Boolean> implements RetryListener { |
增加监听者(可以增加多个,顺序执行)
1 | .withRetryListener(new MyRetryListener<>()) |
核心逻辑
1 | long startTime = System.nanoTime(); |
主要接口
Attempt
一次执行任务
AttemptTimeLimiter
单次任务执行时间限制(如果单次任务执行超时,则终止执行当前任务)
BlockStrategies
任务阻塞策略(通俗的讲就是当前任务执行完,下次任务还没开始这段时间做什么)
默认策略为:BlockStrategies.THREAD_SLEEP_STRATEGY 也就是调用 Thread.sleep(sleepTime);
RetryException
重试异常
RetryListener
自定义重试监听器,可以用于异步记录错误日志
StopStrategy
停止重试策略,提供三种
- StopAfterDelayStrategy :设定一个最长允许的执行时间比如设定最长执行10s,无论任务执行次数,只要重试的时候超出了最长时间,则任务终止,并返回重试异常RetryException
- NeverStopStrategy :不停止,用于需要一直轮训知道返回期望结果的情况
- StopAfterAttemptStrategy :设定最大重试次数,如果超出最大重试次数则停止重试,并返回重试异常
WaitStrategy
等待时长策略(控制时间间隔),返回结果为下次执行时长
- FixedWaitStrategy:固定等待时长策略
- RandomWaitStrategy:随机等待时长策略(可以提供一个最小和最大时长,等待时长为其区间随机值)
- IncrementingWaitStrategy:递增等待时长策略(提供一个初始值和步长,等待时间随重试次数增加而增加)
- ExponentialWaitStrategy:指数等待时长策略
- FibonacciWaitStrategy :Fibonacci 等待时长策略
- ExceptionWaitStrategy :异常时长等待策略
- CompositeWaitStrategy :复合时长等待策略