使用非阻塞重试时的最大重试次数配置?

解读

国内面试官问“非阻塞重试的最大重试次数配置”,并不是想听“3 次”这种数字,而是考察候选人能否把 Spring retry 机制 与 非阻塞语义 对应起来,并指出“最大次数”到底由谁、在哪个阶段、以什么形式决定。
很多候选人把 @Retryable 与 Spring WebFlux 的 Retry 混为一谈,直接回答“maxAttempts=3”,结果被判“只背了注解,没理解非阻塞”。
正确思路是:先分清“非阻塞”= Reactive 栈(Project Reactor / RxJava),再定位到 reactor.util.retry.Retry 这一组 API,最后给出配置入口与默认值。

知识点

  1. 非阻塞重试 ≠ 注解式 @Retryable
    @Retryable 基于 Spring AOP,只能作用于 阻塞方法(Spring 代理对象同步调用),底层是 Thread.sleep,会占用调度线程,不符合非阻塞语义。
  2. Reactive 重试入口
    Spring WebFlux、Spring Cloud Gateway、RSocket 等纯 Reactive 项目,统一使用 Project Reactor 的 retryWhen(Retry) 操作符。
  3. 最大次数配置键
    Reactor 3.3+ 提供 Retry.from(Function<RetrySignal, Retry.RetrySignal>) 工厂,常用实现类 Retry.max(long maxAttempts)。
    • 默认值:Integer.MAX_VALUE(即 2^31-1,几乎无限重试)
    • 配置方式:
      a) 代码级:Retry.max(3)
      b) 配置中心:Spring Boot 2.4+ 在 application.yml 中通过 @ConfigurationProperties 绑定到自定义 Retry Bean,例如
      app.retry.max-attempts=3
      c) Spring Cloud 2020+ 提供 spring.cloud.gateway.retry.max-attempts(网关层)
  4. 退避策略与次数解耦
    Retry.backoff(maxAttempts, Duration) 同时指定次数与退避,次数仍由第一个参数决定。
  5. 异常过滤与次数关系
    Retry.retryOn(IOException.class).maxAttempts(5) 只对特定异常计数,其他异常直接失败,不计入最大次数。

答案

在纯 Reactive 体系(Project Reactor)下,非阻塞重试通过 retryWhen(Retry.max(maxAttempts)) 控制最大次数;
默认值为 Integer.MAX_VALUE,可在代码中硬编码,也可通过 @ConfigurationProperties 读取 application.yml 中的自定义值,例如 app.retry.max-attempts=3。
@Retryable 注解不适用于非阻塞场景,因其基于阻塞式 AOP 拦截。

拓展思考

  1. 生产环境为什么很少把最大次数写死?
    国内大厂普遍把 maxAttempts 与 退避上限 一起放到 Nacos/Apollo 配置中心,支持 热刷新,当下游出现大面积故障时可把次数临时调成 0,直接快速失败,保护自身线程池。
  2. 如何防止“无限重试”把连接池打满?
    结合 Retry.maxAttempts(total) + Retry.filter(predicate) + Metrics(Micrometer)做 实时告警,一旦重试队列堆积超过阈值,立即降级。
  3. Spring 6 的 @RetryableReactive 提案(M1 阶段)未来若落地,将允许在 Kotlin 协程或 Reactive 方法上直接使用注解,届时最大次数可能通过 @RetryableReactive(maxAttempts = 5) 直接声明,但底层仍依赖 Reactor 的 retryWhen,原理不变,可提前关注。