Skip to content

重试器(Retry) ​

工作流程 ​

$retry->call($fn, ...$args) 的执行路径:

  1. 重置本次调用状态
  2. 执行调用:
    • 抛出 \Throwable → 按异常分类判定(见下文),要么等待后重试,要么抛出
    • 正常返回 → 若配置了 retry_on_result 且判定需要重试,等待后重试;否则返回结果
  3. 尝试次数达到 max_attempts(含首次调用)后:
    • fail_after_max_attempts = true → 抛 MaxRetriesExceededException (previous 为最后一次异常;返回值场景则包装判定失败)
    • false(默认)→ 异常场景抛最后一次异常,返回值场景返回最后一次结果
  4. 每次等待前分发 RetryOnRetry 事件,等待通过注入的 Clock::sleep() 完成

decorate() 返回装饰后的 callable,可在调用链上复用。

异常分类 ​

RetryConfig::shouldRetryOnException() 的判定优先级:

  1. ignore_exceptions 列表——命中则不重试、直接抛出(分发 RetryOnIgnoredError)
  2. retryOnException 回调(编程式设置)——配置后由它决定其余异常
  3. retry_exceptions 列表——非空时作为白名单:命中重试,白名单外不重试
  4. 默认——retry_exceptions 为空时重试所有 \Exception

\Error(TypeError 等编程错误)默认不重试;如需重试某个 \Error, 把它加入 retry_exceptions 列表或用 retryOnException 回调放行。

装配默认注入 ignore_exceptions(RpcResponseException、 \InvalidArgumentException),见总览。

与熔断器对称:重试器捕获 \Throwable 但默认只重试 \Exception,熔断器 捕获并统计 \Throwable(\Error 计入失败统计,可通过 ignore_exceptions 豁免)——编程错误会打开熔断但不会触发重试。

配置 ​

配置键 application.resilience.retry,支持 default 段 + 服务名段 + 服务名::方法名 完整段(优先级从低到高),键名通过 setter 注入,使用下划线 写法:

yaml
application:
  resilience:
    retry:
      default:
        max_attempts: 3
        wait_duration: 500
        interval_function: exponential_backoff
        max_interval: 10000
        jitter: 0.1
      demo.DemoService:            # 按服务名覆盖
        max_attempts: 2
      demo.DemoService::getUser:   # 按方法覆盖
        max_attempts: 5
        fail_after_max_attempts: true

中间件按「服务名::方法名」创建实例;直接使用工厂时,名称中 :: 之前的部分 (服务名)也参与配置查找。

配置键默认值说明
max_attempts3最大尝试次数(含首次)
wait_duration500基础等待时长(毫秒)
interval_functionexponential_backoff等待函数名,目前仅支持该值;留空 / 不配置则为固定 wait_duration
max_interval10000单次等待上限(毫秒)
jitter0.1随机抖动比例 [0, 1],0 表示不抖动
retry_exceptions[]需要重试的异常类名列表;非空时作为白名单(白名单外不重试)
ignore_exceptions装配默认不重试直接抛出的异常类名列表
fail_after_max_attemptsfalse耗尽后抛 MaxRetriesExceededException(否则返回最后一次结果)

编程式可额外设置:retry_on_result(返回值重试判定)、retry_on_exception (异常判定回调,完全接管分类)、自定义 interval_function:

php
use kuiper\resilience\retry\RetryConfig;

$config = RetryConfig::builder()
    ->setMaxAttempts(5)
    ->setWaitDuration(200)
    ->setRetryOnResult(fn (object $retry, mixed $result): bool => $result['code'] === 'RATE_LIMITED')
    ->setIntervalFunction(                          // 自定义等待函数
        fn (int $attempts, int $waitDuration, ?\Throwable $e, mixed $result): int => 1000)
    ->build();

退避算法 ​

内置 exponential_backoff(配置文件可用):

text
等待 = min(max_interval, wait_duration × 2^attempts)
  • attempts 从 1 开始:第一次重试等 wait_duration × 2,第二次 ×4,以此类推
  • 指数封顶:attempts ≥ 31 时直接取 max_interval(默认 10s 上限)
  • 基础间隔计算后再截断到 [0, max_interval],最后叠加抖动

抖动:最终等待在 [1 − jitter, 1 + jitter] 的随机因子上缩放(截断后仍不超过 max_interval),避免多个客户端同步重试形成重试风暴。

指标 ​

$retry->getMetrics() 返回四象限统计(历史累计):

方法说明
getNumberOfSuccessfulCallsWithoutRetryAttempt()首次即成功
getNumberOfFailedCallsWithoutRetryAttempt()首次失败且未重试(忽略或不在重试范围)
getNumberOfSuccessfulCallsWithRetryAttempt()重试后成功
getNumberOfFailedCallsWithRetryAttempt()重试耗尽仍失败

事件 ​

事件时机
RetryOnSuccess重试后成功(首次成功不发布)
RetryOnError重试耗尽仍失败
RetryOnIgnoredError异常命中忽略规则(不重试)
RetryOnRetry每次等待重试前(含尝试次数、等待间隔、异常或结果)

异常类型 ​

exception\MaxRetriesExceededException:fail_after_max_attempts = true 时 尝试耗尽抛出,实现 ResilienceException 标记接口。

已知行为与限制 ​

  1. 返回值重试耗尽不抛异常(除非 fail_after_max_attempts = true), RetryOnError 事件的 lastException 为 null。
  2. 重试计数持有在每次 decorate() 调用的内部状态上,同一 RetryImpl 实例 可以被协程并发调用而不互相干扰;但指标计数器是共享累加的(跨调用聚合)。
  3. 重试会放大超时:客户端未配置超时时,下游无响应会让单次调用一直挂住, 重试再乘以尝试次数。务必同时配置 RPC 客户端的 timeout / connect_timeout (见 RPC 客户端最佳实践), 最坏耗时 ≈ max_attempts × timeout。

基于 MIT 许可发布