重试机制的实现

重试作用:

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

远程调用超时、网络突然中断可以重试。外部 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. 3. 贪心思想(todo)

    目录 1. 分配饼干 2. 不重叠区间个数 3. 投飞镖刺破气球 5. 买卖股票最大的收益 6. 买卖股票的最大收益 II 9. 修改一个数成为非递减数组 10. 子数组的最大和 11. 分隔字符串使 ...

  2. Educational Codeforces Round 137 (Rated for Div. 2) - F. Intersection and Union

    (线段树 + 思维)or 动态dp [Problem - F - Codeforces](https://codeforces.com/contest/1743/problem/E) 题意 数轴上有 ...

  3. DRF全局总结

    基础部分 一.创建工程 1.创建虚拟环境 python -m venv 路径 2.安装Django 进入虚拟环境 pip install Django 3.创建项目 django-admin star ...

  4. 解决windows下使用vscode没有函数提示的问题

    vscode支持非常多的扩展,包括支持protobuf语法,非常方便. 笔者近期在使用vscode打开工程(文件夹)情况下,困扰于没有函数提示,例如不同路径的头文件中的函数不提示,库函数不提示,试尽各 ...

  5. ABAP 委外采购收货调用过账bapi

    相关的表: ekko:采购凭证抬头表 用于判断是否委外 ekpo:采购凭证行项目表 用于判断是否委外以及委外采购的数量 resb:获取委外采购单中bom的相应预留 mseg:获取已经委外原材料出库给供 ...

  6. Linux与Windows对比

    1. 前言 Windows是微软为个人台式机/设备或电脑(PC)开发的一系列操作系统.计算机操作系统(OS).每个操作系统都有一个图形用户界面(GUI),桌面允许用户查看所有文件.视频等.Window ...

  7. ubuntu安装nvidia-docker2

    1.配置源: distribution=$(. /etc/os-release;echo $ID$VERSION_ID) && curl -s -L https://nvidia.gi ...

  8. js开发环境如何解决跨域问题

    问题 npm start之后,自己会启动一个端口,比如3000,调用后端服务(比如localhsot:3006/service/list)就会出现跨域,那怎么弄呢? 方式一: webpack设置pro ...

  9. 软件测试肖sir__多线程、多进程、多协程

    Python并发编程有三种方式: 1.多线程Thread(threading)(读音:思来d,丁).多进程Process(multiprocessing).多协程Coroutine(asyncio) ...

  10. Delete `␍` prettier/prettier Vue 可悬浮按钮

    Delete `␍` prettier/prettier 代码格式化不一致,换行符冲突.UNIX/Linux 使用的是 0x0A(LF), DOS/Windows 一直使用 0x0D0A(CRLF) ...