Retry
过滤器
Retry
Filter
Retry
过滤器支持以下参数:
-
retries
: 应该尝试的重试次数。 -
methods
: 应该重试的 HTTP 方法,使用org.springframework.http.HttpMethod
表示。 -
series
: 应该重试的状态码系列,使用org.springframework.http.HttpStatus.Series
表示。 -
exceptions
: 应该重试的抛出异常列表。
如果启用了 Retry
过滤器,将配置以下默认值:
-
retries
: 重试 3 次 -
series
: 5XX 系列 -
methods
: GET 方法 -
exceptions
:IOException
,TimeoutException
和RetryException
以下清单配置了一个重试过滤器:
spring:
cloud:
gateway:
mvc:
routes:
- id: retry_test
uri: http://localhost:8080/flakey
predicates:
- Host=*.retry.com
filters:
- name: Retry
args:
retries: 3
series: SERVER_ERROR
methods: GET,POST
import static org.springframework.cloud.gateway.server.mvc.filter.RetryFilterFunctions.retry;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;
import static org.springframework.cloud.gateway.server.mvc.predicate.GatewayRequestPredicates.host;
@Configuration
class RouteConfiguration {
@Bean
public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
return route("add_request_parameter_route")
.route(host("*.retry.com"), http("https://example.org"))
.filter(retry(config -> config.setRetries(3).setSeries(Set.of(HttpStatus.Series.SERVER_ERROR)).setMethods(Set.of(HttpMethod.GET, HttpMethod.POST))))
.build();
}
}
备注
在使用带有 forward:
前缀的 URL 的重试过滤器时,应谨慎编写目标端点,以便在发生错误时,它不会执行任何可能导致响应发送给客户端并提交的操作。例如,如果目标端点是一个带注解的控制器,目标控制器方法不应返回带有错误状态码的 ResponseEntity
。相反,它应该抛出 Exception
或发出错误信号(例如,通过 Mono.error(ex)
返回值),重试过滤器可以配置为通过重试来处理这些错误。
备注
使用重试过滤器时,它会重试所有在其之后的过滤器。请确保在多次执行后,重试过滤器之后的过滤器结果符合预期。
可以添加一个简化的“快捷方式”表示法,其中包含一个 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
- id: retryshortcut_route
uri: https://example.org
filters:
- Retry=3,INTERNAL_SERVER_ERROR,GET