;
//退避策略
BackOffPolicy backOffPolicy = this.backOffPolicy;
//重试上下文,当前重试次数等都记录在上下文中
RetryContext context = open(retryPolicy, state);
try {
//拦截器模式,执行RetryListener#open
boolean running = doOpenInterceptors(retryCallback, context);
//判断是否可以重试执行
while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
try {//执行RetryCallback回调
return retryCallback.doWithRetry(context);
} catch (Throwable e) {//异常时,要进行下一次重试准备
//遇到异常后,注册该异常的失败次数
registerThrowable(retryPolicy, state, context, e);
//执行RetryListener#onError
doOnErrorInterceptors(retryCallback, context, e);
//如果可以重试,执行退避算法,比如休眠一小段时间后再重试
if (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
backOffPolicy.backOff(backOffContext);
}
//state != null && state.rollbackFor(context.getLastThrowable())
//在有状态重试时,如果是需要执行回滚操作的异常,则立即抛出异常
if (shouldRethrow(retryPolicy, context, state)) {
throw RetryTemplate.<E>wrapIfNecessary(e);
}
}
//如果是有状态重试,且有GLOBAL_STATE属性,则立即跳出重试终止;当抛出的异常是非需要执行回滚操作的异常时,才会执行到此处,CircuitBreakerRetryPolicy会在此跳出循环;
if (state != null && context.hasAttribute(GLOBAL_STATE)) {
break;
}
}
//重试失败后,如果有RecoveryCallback,则执行此回调,否则抛出异常
return handleRetryExhausted(recoveryCallback, context, state);
} catch (Throwable e) {
throw RetryTemplate.<E>wrapIfNecessary(e);
} finally {
//清理环境
close(retryPolicy, context, state, lastException == null || exhausted);
//执行RetryListener#close,比如统计重试信息
doCloseInterceptors(retryCallback, context, lastException);
}
}
有状态or无状态
无状态重试,是在一个循环中执行完重试策略,即重试上下文保持在一个线程上下文中,在一次调用中进行完整的重试策略判断。