如何在 Spring Boot 4 原生重试中获取当前尝试次数以区分软/硬重试上限?
数据小陈
结论
在 RetryPolicy.shouldRetry(Throwable) 这个签名下,API 本身拿不到当前 attempt count。RetryState 只会在 RetryListener 回调里出现,没法直接传给 shouldRetry。如果要实现 soft / default 两套上限,只能自己维护一份跟某一次重试执行绑定的状态。ThreadLocal 可以用,但初始化和清理都要按一次重试执行来做,不能只靠 throwable == null 来清理。
原因
新的 org.springframework.core.retry.RetryPolicy 是偏无状态的策略:每次只根据当前异常判断能不能继续重试,不会把完整执行上下文传进来。你的 beforeRetry 虽然能从 retryState.getExceptions() 统计历史软异常数量,但这个值只在监听器回调内可见,没法直接回传给 shouldRetry 做决策。要共享状态的话,最后还是得用 ThreadLocal 或显式上下文对象。
ThreadLocal 在这里解决的是上下文隔离和清理问题。并发请求通常各自跑在线程上,ThreadLocal 能把它们隔开;但线程池会复用线程,遇到嵌套重试或异步切线程时,计数很容易残留下来,或者被带到下一次执行里。
解决步骤
- 把 soft 计数绑定到一次重试执行,而不是让整个线程在任意时刻共用一个计数。
- 进入重试执行前调用
reset(),在finally里调用clear()。 - 在
shouldRetry中只对SoftRetryableException递增 soft 计数;达到maxSoftAttempts时直接返回false,其他异常交给 delegate。 - 想清楚总重试上限和 soft 上限的关系,别让 soft 分支绕过 delegate 的
maxAttempts。 - 如果重试执行过程中会切线程,改用显式上下文对象或业务状态,不要依赖 ThreadLocal。
代码示例
下面按 TieredRetryPolicy 这个命名整理,原逻辑保留,只把清理点写清楚:
public class TieredRetryPolicy implements RetryPolicy {
private static final ThreadLocal<Integer> SOFT_FAILURE_COUNT =
ThreadLocal.withInitial(() -> 0);
private final RetryPolicy delegate;
private final int maxSoftAttempts;
public TieredRetryPolicy(BackOff backOff, int maxSoftAttempts) {
this.maxSoftAttempts = maxSoftAttempts;
this.delegate = RetryPolicy.builder()
.backOff(backOff)
.includes(SoftRetriableException.class, RetriableException.class)
.excludes(NonRetriableException.class)
.build();
}
public static void reset() {
SOFT_FAILURE_COUNT.remove();
}
public static void clear() {
SOFT_FAILURE_COUNT.remove();
}
@Override
public boolean shouldRetry(Throwable throwable) {
if (throwable == null) {
return true;
}
Throwable cause = resolveMessageExceptionCause(throwable);
if (cause instanceof SoftRetriableException) {
int failures = SOFT_FAILURE_COUNT.get() + 1;
SOFT_FAILURE_COUNT.set(failures);
if (failures >= maxSoftAttempts) {
return false;
}
}
return delegate.shouldRetry(throwable);
}
}
调用重试执行的外层要负责清理:
TieredRetryPolicy.reset();
try {
// 调用你的重试执行入口
return retryOperations.execute(...);
} finally {
TieredRetryPolicy.clear();
}
Bean 配置可以保持这样:
@Bean
public RetryPolicy chroniclerRetryPolicy() {
ExponentialBackOff backOff = new ExponentialBackOff();
backOff.setInitialInterval(props.getInitialInterval());
backOff.setMaxInterval(props.getMaxInterval());
backOff.setMultiplier(props.getMultiplier());
backOff.setMaxAttempts(props.getMaxAttemptsForBackOff());
return new TieredRetryPolicy(backOff, props.getMaxSoftAttempts());
}
RetryListener 里的统计只适合做日志或指标,不要指望它影响本次 shouldRetry 的决策:
@Override
public void beforeRetry(@NonNull RetryPolicy retryPolicy,
@NonNull Retryable<?> retryable,
@NonNull RetryState retryState) {
long softFailures = retryState.getExceptions().stream()
.map(ChroniclerRetryUtil::resolveMessageExceptionCause)
.filter(SoftRetriableException.class::isInstance)
.count();
// 只用于观测/日志;不要假设它会影响本次 shouldRetry 决策
}
注意事项
ThreadLocal的关键是上下文隔离和清理,线程安全不是重点;线程池复用下必须remove()。- 不要只把
throwable == null当作清理点,框架并不保证会以这种方式回调。 - soft 分支直接返回
false时会绕过 delegate,delegate 的maxAttempts也就约束不到 soft 重试。如果需要总上限,要在 soft 分支里额外判断总次数。 - 嵌套重试要保存和恢复外层计数,不能简单
remove(),否则会破坏外层状态。 - 异步或线程切换的场景下 ThreadLocal 会失效,应改用显式上下文对象。
- 如果后续框架提供了带上下文的 policy 扩展点,优先用官方 API;在当前的签名下,无状态 policy 确实拿不到历史尝试次数。
备注:内容仅供参考。
