重试机制的实现

重试作用:

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

远程调用超时、网络突然中断可以重试。外部 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. MATLAB批量处理表格类型文件

    MATLAB版本2020b 问题背景:预处理数据,有若干变压器温度表格,要将变压器运行温度数据提取出来 通过LSTM模型进行温度预测

  2. python的assert和raise的用法

    一.raise用法 在程序运行的过程当中,除了python自动触发的异常外,python也允许我们在程序中手动设置异常,使用 raise 语句即可, 为什么还要手动设置异常呢?首先要分清楚程序发生异常 ...

  3. vue 项目引入 jquery

    一.引入 jquery 1. 方式一 默认会安装最新版本 jquery npm install jquery 2. 方式二 指定版本 npm install jquery@3.6.0 3. 方式三 在 ...

  4. linux查看java堆栈信息_linux进程堆栈大小

    1.查看JAVA进程JVM参数 jinfo -flags pid(进程号) -XX:CICompilerCount=2 最大的并行编译数 -XX:InitialHeapSize=16777216 JV ...

  5. 【Java】@Scheduled注解各参数详解

    每隔5秒执行一次:*/5 * * * * ? 每隔1分钟执行一次:0 */1 * * * ? 每天23点执行一次:0 0 23 * * ? 每天凌晨1点执行一次:0 0 1 * * ? 每月1号凌晨1 ...

  6. 国内centerOs6的yum源都不维护了

    今天需要离线安装slurm.但是用的ubt.  需要fpm一个东西.于是想用原来的centeros联网弄出来. 直接yum 结果??? http://mirrors.163.com/centos/6/ ...

  7. 为win10添加右键“以管理员身份运行MSI”选项

    win+r运行regedit以打开注册表编辑器 定位到HKEY_CLASSES_ROOT\Msi.Package\shell 右键shell,新建 项 项名称为runas 双击runas右边的默认,填 ...

  8. 专业视频图片水印清除工具丨HitPaw Watermark Remover 2.1.3

    软件下载 MAC/Windows HitPaw Watermark Remover 软件介绍 HitPaw Watermark Remover 是一款能够轻松去除图片视频水印的软件.对于有水印的图片视 ...

  9. 直播平台制作,Android 悬浮窗延时5秒返回APP问题

    直播平台制作,Android 悬浮窗延时5秒返回APP问题 案例需求分析:在APP界面,点击Home键后,APP退出后台,同时会打开一个悬浮窗,当用户点击悬浮窗上的按键会返回APP. 出现的问题是:点 ...

  10. Day24:结论的撰写&&openid再次尝试

    今日完成的任务: 1.完成部分总报告结论的撰写. 2.再次尝试获取openid 根据官方文档,wx.login()的回调函数中,需要我们传递生成的用户登录凭证到code2accessToken的接口中 ...