前言:
在日常的开发中,针对某个业务逻辑,我们经常会有执行失败后再重试一次的需求。重试根据异常的不同则会有不同的方案。当然重试也不是失败后立即重试,有可能是等待固定时间后重试,也有可能是指数级等待时间重试,重试N次后则最终判定失败,不再重试。
基于这种需求,阿里开源的datax工具中,也有相应的工具类,就是RetryUtil,笔者就来简单分析下这个util类。
1.datax之RetryUtilpublic final class RetryUtil {
private static final Logger LOG = LoggerFactory.getLogger(RetryUtil.class);
private static final long MAX_SLEEP_MILLISECOND = 256 * 1000;
/**
* 重试次数工具方法.
*
* @param callable 实际逻辑
* @param retryTimes 最大重试次数(>1)
* @param sleepTimeInMilliSecond 运行失败后休眠对应时间再重试
* @param exponential 休眠时间是否指数递增
* @param 返回值类型
* @return 经过重试的callable的执行结果
*/
public static T executeWithRetry(Callable callable,
int retryTimes,
long sleepTimeInMilliSecond,
boolean exponential) throws Exception {
Retry retry = new Retry();
return retry.doRetry(callable, retryTimes, sleepTimeInMilliSecond, exponential, null);
}
/**
* 重试次数工具方法.
*
* @param callable 实际逻辑
* @param retryTimes 最大重试次数(>1)
* @param sleepTimeInMilliSecond 运行失败后休眠对应时间再重试
* @param exponential 休眠时间是否指数递增
* @param 返回值类型
* @param retryExceptionClasss 出现指定的异常类型时才进行重试
* @return 经过重试的callable的执行结果
*/
public static T executeWithRetry(Callable callable,
int retryTimes,
long sleepTimeInMilliSecond,
boolean exponential,
List> retryExceptionClasss)
throws Exception {
// 参数校验
if (null == callable) {
throw new IllegalArgumentException("系统编程错误, 入参callable不能为空 ! ");
}
if (retryTimes < 1) {
throw new IllegalArgumentException(String.format(
"系统编程错误, 入参retrytime[%d]不能小于1 !", retryTimes));
}
Exception saveException = null;
for (int i = 0; i < retryTimes; i++) {
try {
// 执行方法调用
return call(callable);
} catch (Exception e) {
saveException = e;
if (i == 0) {
LOG.error(String.format("Exception when calling callable, 异常Msg:%s", saveException.getMessage()), saveException);
}
// 如果指定了对应的异常类,则判断当前e是否就是对应的异常类,是的话则执行重试,否则直接抛出异常
if (null != retryExceptionClasss && !retryExceptionClasss.isEmpty()) {
boolean needRetry = false;
for (Class eachExceptionClass : retryExceptionClasss) {
if (eachExceptionClass == e.getClass()) {
needRetry = true;
break;
}
}
if (!needRetry) {
throw saveException;
}
}
// 不超过最大重试次数则执行后续重试逻辑
if (i + 1 < retryTimes && sleepTimeInMilliSecond > 0) {
long startTime = System.currentTimeMillis();
// 根据入参决定休息多久之后执行重试逻辑,最大不超过MAX_SLEEP_MILLISECOND
long timeToSleep;
if (exponential) {
timeToSleep = sleepTimeInMilliSecond * (long) Math.pow(2, i);
if(timeToSleep >= MAX_SLEEP_MILLISECOND) {
timeToSleep = MAX_SLEEP_MILLISECOND;
}
} else {
timeToSleep = sleepTimeInMilliSecond;
if(timeToSleep >= MAX_SLEEP_MILLISECOND) {
timeToSleep = MAX_SLEEP_MILLISECOND;
}
}
try {
// 当前执行线程沉睡
Thread.sleep(timeToSleep);
} catch (InterruptedException ignored) {
}
long realTimeSleep = System.currentTimeMillis()-startTime;
LOG.error(String.format("Exception when calling callable, 即将尝试执行第%s次重试.本次重试计划等待[%s]ms,实际等待[%s]ms, 异常Msg:[%s]",
i+1, timeToSleep,realTimeSleep, e.getMessage()));
}
}
}
throw saveException;
}
protected T call(Callable callable) throws Exception {
return callable.call();
}
}
Retry重试逻辑还是比较简单的,根据不同的入参,控制重试的休眠事件以及是否重试的相关逻辑。
需要注意的是,重试中的休眠逻辑会直接在当前执行线程中执行,如果使用者不想休眠当前线程,可以考虑使用RetryUtil的第三个方法,也就是下面的AsyncRetry的逻辑。
3.AsyncRetry异步执行重试逻辑// 直接继承了Retry类
private static class AsyncRetry extends Retry {
private long timeoutMs;
private ThreadPoolExecutor executor;
public AsyncRetry(long timeoutMs, ThreadPoolExecutor executor) {
this.timeoutMs = timeoutMs;
this.executor = executor;
}
/**
* 使用传入的线程池异步执行任务,并且等待。
*
* future.get()方法,等待指定的毫秒数。如果任务在超时时间内结束,则正常返回。
* 如果抛异常(可能是执行超时、执行异常、被其他线程cancel或interrupt),都记录日志并且网上抛异常。
* 正常和非正常的情况都会判断任务是否结束,如果没有结束,则cancel任务。cancel参数为true,表示即使
* 任务正在执行,也会interrupt线程。
*
* @param callable
* @param
* @return
* @throws Exception
*/
@Override
protected T call(Callable callable) throws Exception {
// 重写后的call()方法,在执行重试时,直接交由Executor执行,避免了当前线程被阻塞
Future future = executor.submit(callable);
try {
// 在规定时间内获取执行结果
return future.get(timeoutMs, TimeUnit.MILLISECONDS);
} catch (Exception e) {
// 规定时间内没有获取到结果则直接抛出异常
LOG.warn("Try once failed", e);
throw e;
} finally {
if (!future.isDone()) {
future.cancel(true);
LOG.warn("Try once task not done, cancel it, active count: " + executor.getActiveCount());
}
}
}
}
总结:
读者可以好好比较下Retry和AsyncRetry两者之间的区别。在适当的场景选择适当的重试对象。