重试机制的实现

重试作用:

对于重试是有场景限制的,参数校验不合法、写操作等(要考虑写是否幂等)都不适合重试。

远程调用超时、网络突然中断可以重试。外部 RPC 调用,或者数据入库等操作,如果一次操作失败,可以进行多次重试,提高调用成功的可能性

优雅的重试机制要具备几点:

  • 无侵入:这个好理解,不改动当前的业务逻辑,对于需要重试的地方,可以很简单的实现
  • 可配置:包括重试次数,重试的间隔时间,是否使用异步方式等
  • 通用性:最好是无改动(或者很小改动)的支持绝大部分的场景,拿过来直接可用

重试实现方式

1 切面方式

在需要添加重试的方法上添加一个用于重试的自定义注解,然后在切面中实现重试的逻辑,主要的配置参数则根据注解中的选项来初始化

优点:

  • 真正的无侵入

缺点:

  • 某些方法无法被切面拦截的场景无法覆盖(如spring-aop无法切私有方法,final方法)

    直接使用aspecj则有些小复杂;如果用spring-aop,则只能切被spring容器管理的bean

2 消息总线方式

这个也比较容易理解,在需要重试的方法中,发送一个消息,并将业务逻辑作为回调方法传入;由一个订阅了重试消息的consumer来执行重试的业务逻辑

优点:

  • 重试机制不受任何限制,即在任何地方你都可以使用

    利用EventBus框架,可以非常容易把框架搭起来

缺点:

  • 业务侵入,需要在重试的业务处,主动发起一条重试消息

    调试理解复杂(消息总线方式的最大优点和缺点,就是过于灵活了,你可能都不知道什么地方处理这个消息,特别是新的童鞋来维护这段代码时)

    如果要获取返回结果,不太好处理, 上下文参数不好处理

3 模板方式(定义一个抽象类,业务逻辑进行继承) 类似与代理模式

4 spring-retry框架(注解)

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.newBuilder()
//异常重试
.retryIfException()
//运行时异常
.retryIfRuntimeException()
//某种类型的异常
.retryIfExceptionOfType(ServiceRuntimeException.class)
//符合异常条件
.retryIfException(Predicates.equalTo(new Exception()))
//结果符合某种条件
.retryIfResult(Predicates.equalTo(false))
//重试等待时间
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
//停止条件
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
//监听器
.withRetryListener(new MyRetryListener()) //重试限制器(每一次执行的时间)
.withAttemptTimeLimiter(AttemptTimeLimiters.fixedTimeLimit(1, TimeUnit.SECONDS))
.build(); //监听器
.withRetryListener(new RetryListener() {
@Override
public <V> void onRetry(Attempt<V> attempt) {
log.info("listener receive attempt={}",attempt);
}
})

1.3 主逻辑放在callable里,传给retryer进行调用

public int mockQueryDB() {
Callable<Integer> callable = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return doQuery();
}
};
} //源码
public V call(Callable<V> callable) throws ExecutionException, RetryException{ } @FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}

1.4 执行

根据配置,当发生异常时,会重试,最多执行3次。每次尝试中间会等待3秒。

如果执行3次,仍然报错,那么retryer.call会报RetryException:

int result;
try {
result = retryer.call(callable);
//或者 返回值为泛型 最终为object 需要强制转化
result = (int) requestRetryer.call(() -> doQuery());
} catch (Exception e) {
result = -1;
}
return result; com.github.rholder.retry.RetryException: Retrying failed to complete successfully after 3 attempts.

2. retryIfException

guava retry支持多种条件下重试

2.1 retryIfException()

这个就是在任何异常发生时,都会进行重试。

.retryIfException()

2.2 retryIfRuntimeException()

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

.retryIfRuntimeException()

2.3 retryIfExceptionOfType

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

.retryIfExceptionOfType(DBException.class)

2.4 retryIfException(@Nonnull Predicate 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的attempTime次幂

// 第一二次之间等待 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

重试前休眠minimumTime~maximumTime之间随机时间

//等待时间为 0 到3秒 之间的随机时间
.withWaitStrategy(WaitStrategies.randomWait(3, TimeUnit.SECONDS)) //等待时间为 1秒到3秒之间的随机时间
.withWaitStrategy(WaitStrategies.randomWait(1, TimeUnit.SECONDS, 3, TimeUnit.SECONDS))

5.6 WaitStrategies.incrementingWait

第一次重试休眠initialSleepTime,后续每次重试前休眠时间线性递增increment。例如,第一二次之间等待1秒,接下来每次增加3秒。

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

5.7 WaitStrategies.noWait

不等待,直接重试。

.withWaitStrategy(WaitStrategies.noWait())

5.8 WaitStrategies.join (CompositeWaitStrategy)

WaitStrategies.join可以将多种等待策略组合起来,等待时间为多个策略的时间和。

例如,join了exponentialWait和fixedWait:

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

6 监听器

public class MyRetryListener<String> implements RetryListener {

   @Override
public <String> void onRetry(Attempt<String> attempt) { // 第几次重试,(注意:第一次重试其实是第一次调用)
System.out.print("[retry]time=" + attempt.getAttemptNumber()); // 距离第一次重试的延迟
System.out.print("[retry]delay=" + attempt.getDelaySinceFirstAttempt()); // 重试结果: 是异常终止, 还是正常返回
System.out.print("[retry]hasException=" + attempt.hasException());
System.out.print("[retry]hasResult=" + attempt.hasResult()); // 是什么原因导致异常
if (attempt.hasException()) {
System.out.print("[retry]causeBy=" + attempt.getExceptionCause().toString());
} else {
// 正常返回时的结果
System.out.print("[retry]result=" + attempt.getResult());
} // bad practice: 增加了额外的异常处理代码
try {
String result = attempt.get();
System.out.print("rude get=" + result);
} catch (ExecutionException e) {
System.err.println("this attempt produce exception." + e.getCause().toString());
} }
}

最新文章

  1. O(1)效率的表面模糊算法优化。
  2. IPC操作时IPC_CREAT和IPC_EXCL选项的说明
  3. 使用vbs脚本进行批量编码转换
  4. 基于C#的MongoDB数据库开发应用(2)--MongoDB数据库的C#开发
  5. win7远程桌面连接不上,解决办法
  6. day08
  7. yii 事物
  8. 12. Android框架和工具之 StringUtils(字符串操作)
  9. 关于try...catch...finally中return的疑惑
  10. linux下的java远程调试jpda+tomcat
  11. Linux下MySql启动时报错
  12. RedHat升级内核成功
  13. android Intent.createChooser 应用选择
  14. C语言老司机学Python (一)
  15. ngxin 配置ssl
  16. 真正的轻量级WebService框架——使用JAX-WS(JWS)发布WebService(转载)
  17. java程序员随笔
  18. java容器的理解(collection)
  19. C++关于sort和priority_queue的运算符重载
  20. Centos7 安装Nodejs

热门文章

  1. mybatis动态标签——choose、when、otherwise
  2. 【MySQL 服务器参数优化】
  3. 数值分析之解线性方程组的直接方法 5.X
  4. vue项目去掉网页滚动条
  5. nuxt 服务端渲染注意事项
  6. make 编译笔记
  7. Java复习篇3---基础概念
  8. Java笔记_this关键字_HomeWork(5 - 9 题)
  9. 》》》Win10配置Jdk环境变量
  10. Jenkins+Docker 实现一键自动化部署项目!