跳到主要内容
版本:5.0.1

Retry GatewayFilter 工厂

DeepSeek V3 中英对照 Retry GatewayFilter Factory Retry GatewayFilter Factory

Retry GatewayFilter 工厂支持以下参数:

  • retries: 应尝试的重试次数。

  • statuses: 应重试的 HTTP 状态码,使用 org.springframework.http.HttpStatus 表示。

  • methods: 应重试的 HTTP 方法,使用 org.springframework.http.HttpMethod 表示。

  • series: 应重试的状态码系列,使用 org.springframework.http.HttpStatus.Series 表示。

  • exceptions: 应重试的抛出异常列表。

  • backoff: 为重试配置的指数退避。重试在退避间隔 firstBackoff * (factor ^ n) 后执行,其中 n 是迭代次数。如果配置了 maxBackoff,则应用的最大退避时间限制为 maxBackoff。如果 basedOnPreviousValue 为 true,则退避时间使用 prevBackoff * factor 计算。

  • jitter: 为重试配置的随机抖动。生成一个介于 [backoff - backoff*randomFactor, backoff + backoff*randomFactor] 之间的退避时间。

  • timeout: 为重试配置的超时时间。

如果启用,Retry 过滤器将配置以下默认值:

  • retries: 三次

  • series: 5XX 系列

  • methods: GET 方法

  • exceptions: IOException 和 TimeoutException

  • backoff: 禁用

  • jitter: 禁用

  • timeout: 无限制

以下清单配置了一个重试 GatewayFilter:

spring:
cloud:
gateway:
routes:
- id: retry_test
uri: http://localhost:8080/flakey
predicates:
- Host=*.retry.com
filters:
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY
methods: GET,POST
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor: 2
basedOnPreviousValue: false
jitter:
randomFactor: 0.5
timeout: 100ms
备注

当使用带有 forward: 前缀 URL 的重试过滤器时,应谨慎编写目标端点,以便在发生错误时,它不会执行任何可能导致向客户端发送并提交响应的操作。例如,如果目标端点是一个带注解的控制器,目标控制器方法不应返回带有错误状态码的 ResponseEntity。相反,它应该抛出一个 Exception 或发出错误信号(例如,通过 Mono.error(ex) 返回值),然后可以配置重试过滤器通过重试来处理该错误。

备注

使用重试过滤器时,它会重试其后的所有过滤器。请确保重试过滤器之后的过滤器在多次执行时,其结果符合预期。

注意

当将重试过滤器与任何带有请求体的 HTTP 方法一起使用时,请求体将被缓存,网关可能会受到内存限制。请求体缓存在由 ServerWebExchangeUtils.CACHED_REQUEST_BODY_ATTR 定义的请求属性中。该对象的类型为 org.springframework.core.io.buffer.DataBuffer。

可以通过单个 status 和 method 添加简化的“快捷”表示法。

以下两个示例是等价的:

spring:
cloud:
gateway:
routes:
- id: retry_route
uri: https://example.org
filters:
- name: Retry
args:
retries: 3
statuses: INTERNAL_SERVER_ERROR
methods: GET
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor: 2
basedOnPreviousValue: false
jitter:
randomFactor: 0.5
timeout: 100ms

- id: retryshortcut_route
uri: https://example.org
filters:
- Retry=3,INTERNAL_SERVER_ERROR,GET,10ms,50ms,2,false,0.5,100ms