重试机制的实现

重试作用:

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

远程调用超时、网络突然中断可以重试。外部 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());
} }
}

重试机制的实现(Guava Retry)的更多相关文章

  1. Java之Retry重试机制详解

    应用中需要实现一个功能: 需要将数据上传到远程存储服务,同时在返回处理成功情况下做其他操作.这个功能不复杂,分为两个步骤:第一步调用远程的Rest服务上传数据后对返回的结果进行处理:第二步拿到第一步结 ...

  2. guava的重试机制guava-retrying使用

    1,添加maven依赖 <dependency> <groupId>com.github.rholder</groupId> <artifactId>g ...

  3. springboot 整合retry(重试机制)

    当我们调用一个接口可能由于网络等原因造成第一次失败,再去尝试就成功了,这就是重试机制,spring支持重试机制,并且在Spring Cloud中可以与Hystaix结合使用,可以避免访问到已经不正常的 ...

  4. retry之python重试机制

    安装 pip install retry Retry装饰器 retry(exceptions=Exception, tries=-1, delay=0, max_delay=None, backoff ...

  5. spring-retry 重试机制

    业务场景 应用中需要实现一个功能: 需要将数据上传到远程存储服务,同时在返回处理成功情况下做其他操作.这个功能不复杂,分为两个步骤:第一步调用远程的Rest服务逻辑包装给处理方法返回处理结果:第二步拿 ...

  6. 【Dubbo 源码解析】07_Dubbo 重试机制

    Dubbo 重试机制 通过前面 Dubbo 服务发现&引用 的分析,我们知道,Dubbo 的重试机制是通过 com.alibaba.dubbo.rpc.cluster.support.Fail ...

  7. Spring Cloud 请求重试机制核心代码分析

    场景 发布微服务的操作一般都是打完新代码的包,kill掉在跑的应用,替换新的包,启动. spring cloud 中使用eureka为注册中心,它是允许服务列表数据的延迟性的,就是说即使应用已经不在服 ...

  8. Volley超时重试机制

    基础用法 Volley为开发者提供了可配置的超时重试机制,我们在使用时只需要为我们的Request设置自定义的RetryPolicy即可. 参考设置代码如下: int DEFAULT_TIMEOUT_ ...

  9. SpringCloud | FeignClient和Ribbon重试机制区别与联系

    在spring cloud体系项目中,引入的重试机制保证了高可用的同时,也会带来一些其它的问题,如幂等操作或一些没必要的重试. 今天就来分别分析一下 FeignClient 和 Ribbon 重试机制 ...

  10. Spring Cloud重试机制与各组件的重试总结

    SpringCloud重试机制配置 首先声明一点,这里的重试并不是报错以后的重试,而是负载均衡客户端发现远程请求实例不可到达后,去重试其他实例. ? 1 2 3 4 5 6 7 8 @Bean @Lo ...

随机推荐

  1. Mybatis-Plus 之BaseMapper 方法详解

    package com.itheima.dao; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomido ...

  2. 获取小程序toast控件

    Toast 含义 为了给当前视图显示一个浮动的显示块,与dialog不同它永远不会获得焦点 显示时间有限,根据用户设置的显示时间后自动消失 本身是个系统级别的控件,它归属系统settings,当一个a ...

  3. 【面试题】面试官:请你实现一个深拷贝,那如果是正则/set/函数怎么拷贝?

    一.面试官灵魂三连问: 你知道哪些拷贝的方法? 让你实现一个深拷贝怎么实现? 那像正则.Set.Map.函数等如何拷贝? 二.浅拷贝方法 自己创建一个新对象,来接收你要重新复制或引用的对象值.如果对象 ...

  4. 不需要鼠标交互的UI去掉RaycastTarget

    UI事件会在EventSystem在Update的Process触发.UGUI会遍历屏幕中所有RaycastTarget是true的UI,接着就会发射线,并且排序找到玩家最先触发的那个UI,在抛出事件 ...

  5. Linux Qt编译时出现has modification time int the future的解决方法

    问题场景:我在window系统上合并完代码后,将代码通过TF卡拖到了Debian系统的开发板子上(为什么我不用Winscp或者xhttp传呢?因为网线被同事拿走了...),然后就报这个错. 网上查阅资 ...

  6. leecode72. 编辑距离

    72. 编辑距离 给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 . 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个 ...

  7. python_类 对象 属性

    1, 类 (class) 类的概念表示某种对象的集合,用于表示某一种相同对象的模板.例如:人作为一个类 由这个"人"类定义出来的内容就是这个类定义出来的对象,类还拥有属性和功能,属 ...

  8. VS+QT创建的项目 UI界面更新控件,代码里识别不到

    1.如果安装了小番茄,看下自己的小番茄的设置里,source of C/C++ content需要选择 Default Intellisense,选择visual assist是识别不到的,具体是为什 ...

  9. js检测数组是否有重复的数据,

    function(arr){ let hash={} for (const key in arr){ if(hash[arr[key]]){ return true } hash[arr[key]]= ...

  10. Python学习笔记(四)算术运算符

    一.算术运算符 运算符 说明 实例 结果 + 加 12.45 + 15 27.45 - 减 4.56 - 0.26 4.3 * 乘 5 * 3.6 18.0 / 除法(和数学中的规则一样) 7 / 2 ...