非常简洁地重试Retry组件,使用起来杠杠的

开发 前端
今天给大家带来一个retry重试组件,流行度很高,即是guava-retrying组件。功能简洁强大,是出门旅行的必备工具。

前言

小伙伴是不是经常遇到接口调用异常,超时的场景?尤其网络抖动导致timeout超时的场景,我们一般产品就会叫我们要重试几次。

很多小伙伴的实现方式是写个循环调用;

for(int i=1;i<=3;i++{
try{
if(doExec()){
break;
}
}catch{
}
}

这种实现方式是比较简单,但非常不灵活,不能针对很多种场景。今天老顾给大家带来一个retry重试组件,流行度很高,即是guava-retrying组件。功能简洁强大,是出门旅行的必备工具。

依赖引用

<dependency>
<groupId>com.github.rholder</groupId>
<artifactId>guava-retrying</artifactId>
<version>2.0.0</version>
<!-- 排除与guava重复的依赖 -->
<!-- <exclusions>-->
<!-- <exclusion>-->
<!-- <groupId>com.google.guava</groupId>-->
<!-- <artifactId>guava</artifactId>-->
<!-- </exclusion>-->
<!-- <exclusion>-->
<!-- <groupId>com.google.code.findbugs</groupId>-->
<!-- <artifactId>jsr305</artifactId>-->
<!-- </exclusion>-->
<!-- </exclusions>-->
</dependency>

guava-retrying包中应用有相关的guava版本依赖,如果和自身项目冲突可以排除。

示例

执行方法

@Service
public class RetryService {
private static Logger logger = LoggerFactory.getLogger(RetryService.class);
private AtomicInteger count = new AtomicInteger(0);
public int doExec(){
logger.info("调用了{}次",count.incrementAndGet());
if (count.get() % 2 == 0){
throw new Exception("----->异常了哦");
}
return count.get();
}
}

里面定义了doExec方法,每次调用count加1,如果是2的倍数就抛异常。

调用方法

public String test01(){
Retryer<Integer> retryer = RetryerBuilder.<Integer>newBuilder()
.retryIfRuntimeException()
//retryIfResult 表达式返回true,则重试
.retryIfResult(result -> {
if (result % 3 == 0){
logger.info("----->应该重试了");
return true;
}
return false;
})
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();
try {
retryer.call(() -> retryService.doExec());
} catch (ExecutionException e) {
logger.error("异常1:{}",e.getMessage());
} catch (RetryException e) {
logger.error("异常:{}",e.getMessage());
}
return "ok";
}

从上面代码中,我们就可以实现条件重试。

guava的retry的思想可分为重试条件、停止重试策略、重试间隔策略

一、重试条件

表示在什么情况下,进行重试。retry组件中的RetryerBuilder的retryIfXXX()方法用来设置在什么情况下进行重试,总体上可以分为根据执行异常进行重试和根据方法执行结果进行重试两类。

根据异常重试

1、retryIfException() 当方法执行抛出异常Exception时重试

2、retryIfRuntimeException()当方法执行抛出异常RuntimeException时重试

3、retryIfExceptionOfType(exceptionClass)当方法执行抛出异常具体哪个异常时重试

4、retryIfException(Predicate p)自定义异常什么情况下重试

根据返回结果重试

retryIfResult(@Nonnull Predicate<V> resultPredicate)根据返回值判断是否重试。

//返回true时,重试
.retryIfResult(result -> {
if (result % 3 == 0){
logger.info("----->应该重试了");
return true;
}
return false;
})

上面的result代表的是返回值,判断返回值对3取余,返回true时则进行重试。

二、停止重试策略

重试组件需要提供停止重试的策略withStopStrategy,最简单的方式就是重试几次

1、StopAfterAttemptStrategy

从字面上面就知道什么意思,即在执行次数达到指定次数之后停止重试。

.withStopStrategy(StopStrategies.stopAfterAttempt(3))

2、NeverStopStrategy

此策略永远重试,一直重试

.withStopStrategy(StopStrategies.neverStop())

3、StopAfterDelayStrategy

设定一个最长允许的执行时间;比如设定最长执行10s,无论任务执行次数,只要重试的时候与第一次执行的时间差,超出了最长时间,则任务终止,并返回重试异常RetryException

.withStopStrategy(StopStrategies.stopAfterDelay(10,TimeUnit.SECONDS))

三、重试间隔策略

在重试场景中,我们最好有个重试的间隔,如果没有间隔,很有可能连续的重试都会失败。

WaitStrategy

1、FixedWaitStrategy

固定时长重试间隔。

.withWaitStrategy(WaitStrategies.fixedWait(1,TimeUnit.SECONDS))

上面即是重试间隔为1秒。

2、RandomWaitStrategy

随机的间隔时长

.withWaitStrategy(WaitStrategies.randomWait(1,TimeUnit.SECONDS,5,TimeUnit.SECONDS))

第1个参数是最小间隔时长,第二个参数最大间隔时长;介于两者之间随机取一个时长。

3、IncrementingWaitStrategy

递增间隔时长,即每次任务重试间隔时间逐步递增,越来越长

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

该策略输入一个起始间隔时间值和一个递增步长,然后每次等待的时长都递增increment时长。

4、ExceptionWaitStrategy

根据不同的异常,决定不同的间隔时长。

.withWaitStrategy(WaitStrategies.exceptionWait(Exception.class, new Function<Exception, Long>() {
@Override
public @Nullable Long apply(@Nullable Exception input) {
if (input instanceof NullPointerException){
return 1 * 1000L;
}else if (input instanceof IndexOutOfBoundsException){
return 2 * 1000L;
}else if (input instanceof IllegalStateException){
return 3 * 1000L;
}
return 0L;
}
}))

上面的代码 一看就知道了。

上面是常见的等待策略,还有几个不常用的等待策略,小伙伴们自行查阅。

到了这里,我们感觉还缺失了非常重要的一个模块;即是我们能否知道任务有没有经过重试?或者我们需要记录一下重试次数,或者重试的时候,弄一个error日志告警,帮助我们关注系统的稳健。

我们来介绍一下重试监听器。

重试监听器RetryListener

当发送重试时,会调用RetryListener的onRetry方法,这样的话我们就可以做一些自定义的重试的额外任务。

定义一个类,继承RetryListener接口

public class MyRetryListener implements RetryListener {

private static Logger logger = LoggerFactory.getLogger(MyRetryListener.class);

@Override
public <Integer> void onRetry(Attempt<Integer> attempt) {
if (attempt.hasResult()){
logger.info("===>方法返回的结果:{}",attempt.getResult());
}

if (attempt.hasException()){
logger.info("===>第{}次执行,异常:{}",attempt.getAttemptNumber(),attempt.getExceptionCause()==null ? "" : attempt.getExceptionCause().getMessage());
return;
}
logger.info("===>第{}次执行",attempt.getAttemptNumber());
}
}

在RetryerBuilder中加入;

.withRetryListener(new MyRetryListener())

这样就实现了监听业务

重试原理

guava-retrying的组件功能还是比较强大的,我们可以看一下核心的代码

public V call(Callable<V> callable) throws ExecutionException, RetryException {
long startTime = System.nanoTime();

// 执行次数从1开始
for (int attemptNumber = 1; ; attemptNumber++) {
Attempt<V> attempt;
try {
// 尝试执行
V result = attemptTimeLimiter.call(callable);

// 执行成功则将结果封装为ResultAttempt
attempt = new Retryer.ResultAttempt<V>(result, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
} catch (Throwable t) {
// 执行异常则将结果封装为ExceptionAttempt
attempt = new Retryer.ExceptionAttempt<V>(t, attemptNumber, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
}

// 这里将执行结果传给RetryListener做一些额外事情
for (RetryListener listener : listeners) {
listener.onRetry(attempt);
}
// 这个就是决定是否要进行重试的地方,如果不进行重试直接返回结果,执行成功就返回结果,执行失败就返回异常
if (!rejectionPredicate.apply(attempt)) {
return attempt.get();
}

// 到这里,说明需要进行重试,则此时先决定是否到达了停止重试的时机,如果到达了则直接返回异常
if (stopStrategy.shouldStop(attempt)) {
throw new RetryException(attemptNumber, attempt);
} else {
// 决定重试时间间隔
long sleepTime = waitStrategy.computeSleepTime(attempt);
try {
// 进行阻塞
blockStrategy.block(sleepTime);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RetryException(attemptNumber, attempt);
}
}
}

}
责任编辑:武晓燕 来源: 今日头条
相关推荐

2021-06-30 09:20:18

NuShell工具Linux

2021-03-10 09:54:43

RustNuShell系统

2012-12-17 09:54:08

2021-01-29 17:40:00

Flyme安卓手机安全

2021-09-29 07:13:12

编程 Python Merge

2019-12-03 18:37:00

华为Mate X

2012-07-11 09:34:39

2022-05-22 21:16:46

TypeScriptOmit 工具

2009-10-21 09:03:23

VB.NET Web

2020-07-06 15:13:16

安卓AirDrop无线传输

2020-01-06 15:00:43

Linux电脑发行版

2021-09-18 08:52:45

人工智能

2024-04-02 09:32:08

Spring@Retry开发者

2015-05-28 10:35:07

前端gulpdemo

2022-11-07 09:25:02

Kafka存储架构

2016-03-17 09:45:17

react双向绑定插件

2016-06-12 09:28:46

Ubuntu 16.0升级Linux

2020-11-27 14:28:13

数据分析工具数据库

2021-04-18 07:18:31

Chrome

2022-12-27 17:56:40

ack机制RocketMQ
点赞
收藏

51CTO技术栈公众号