重试机制的实现

重试作用:

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

远程调用超时、网络突然中断可以重试。外部 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. openssl国密算法库

    openssl国密算法库 一.开发背景 openssl是一个功能丰富且自包含的开源安全工具箱.它提供的主要功能有:SSL协议实现(包括SSLv2.SSLv3和TLSv1).大量软算法(对称/非对称/摘 ...

  2. 后台Mysql存储过程调用

    https://blog.csdn.net/weixin_43695211/article/details/127883536

  3. Mysql习题系列(一):基本select语句与运算符

    Mysql8.0习题系列 软件下载地址 提取码:7v7u 数据下载地址 提取码:e6p9 文章目录 Mysql8.0习题系列 1. 基本select语句 1.1 题目 1.2答案 1.查询员工12个月 ...

  4. NSIS 自定义界面,下载并安装Net.Framework4.8

    以 ScreenToGif 这款软件为例,详细讲解如何在安装的过程中检测并下载net包进行安装. 前言 1.ScreenToGif 是一款开源的截屏软件,依赖于Net.Framework环境 2.本文 ...

  5. N63050 第一周运维作业

    1.按系列罗列Linux的发行版,并描述不同发行版之间的联系与区别. slackware:SUSE Linux Enterprise Server (SLES) , OpenSuse桌面debian: ...

  6. System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.Compression.FileSystem系统找不到指定的文件

    错误:System.IO.FileNotFoundException: Could not load file or assembly 'System.IO.Compression.FileSyste ...

  7. JavaSE——.replace()方法替换内容

    package com.zhao.stringtest; public class Test5 { //.replace()方法替换词汇 public static void main(String[ ...

  8. 第1关—print()函数与转换

    Print()函数的用法有以下几种:单枪匹马--不带引号.搭配单引号.搭配双引号.搭配三引号,我们逐个见识下吧!  1.无引号       注意,这里的括号一定要用[英文括号],不然会报错 impor ...

  9. 硬件IIC的重映射使用问题

    目录 沁恒的蓝牙系列芯片,有映射硬件模块去其他引脚的功能,可以配置各芯片的功能引脚重映射寄存器(R16_PIN_ALTERNATE),或者使用函数GPIOPinRemap函数进行配置. 比如说想要配置 ...

  10. 思科数据中心CCIE稳定PASS

    乾颐堂DC数据中心CCIE,在增加新题的情况下一次PASS! 目前笔试.lab都在过人,需要备考的同学联系乾颐堂,机时充足!