Retry 過濾器
Retry 過濾器會根據類路徑中可用的內容自動選擇合適的重試實現。
-
如果 Spring Retry 在類路徑中,過濾器預設使用
GatewayRetryFilterFunctions(基於 Spring Retry)。 -
如果 Spring Retry 不在類路徑中,過濾器會自動使用
FrameworkRetryFilterFunctions(基於 Spring Framework 7 中的重試功能)。
Spring Retry 已進入僅維護模式。一旦 Spring Retry 不再維護,Retry 過濾器將專門使用 Framework 重試實現(FrameworkRetryFilterFunctions),並且基於 Spring Retry 的實現將被移除。 |
即使 Spring Retry 在類路徑中,您也可以透過在配置中設定 spring.cloud.gateway.server.webmvc.use-framework-retry-filter=true 來強制使用 Framework 重試過濾器。 |
Retry 過濾器支援以下引數:
-
retries:應嘗試的重試次數。 -
methods:應重試的 HTTP 方法,使用org.springframework.http.HttpMethod表示。 -
series:應重試的狀態碼系列,使用org.springframework.http.HttpStatus.Series表示。 -
exceptions:應重試的丟擲異常列表。 -
cacheBody:一個標誌,指示是否應快取請求體。如果設定為true,則必須使用adaptCacheBody過濾器將快取的請求體傳送到下游。
如果啟用,Retry 過濾器配置了以下預設值:
-
retries:三次 -
series:5XX 系列 -
methods:GET 方法 -
exceptions:IOException、TimeoutException和RetryException -
cacheBody:false
將 cacheBody 設定為 true 會導致閘道器將整個請求體讀入記憶體。應謹慎使用此功能。 |
以下清單配置了一個 Retry 過濾器:
application.yml
spring:
cloud:
gateway:
mvc:
routes:
- id: retry_route
uri: https://:8080/flakey
predicates:
- Host=*.retry.com
filters:
- name: Retry
args:
retries: 3
series: SERVER_ERROR
methods: GET,POST
cacheBody: true
- name: AdaptCachedBody
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.filter.FilterFunctions.adaptCachedBody;
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> gatewayRouterFunctionsRetry() {
return route("retry_route")
.route(host("*.retry.com"), http())
.before(uri("https://:8080/flakey"))
.filter(retry(config -> config.setRetries(3)
.setSeries(Set.of(HttpStatus.Series.SERVER_ERROR))
.setMethods(Set.of(HttpMethod.GET, HttpMethod.POST))
.setCacheBody(true)))
.filter(adaptCachedBody())
.build();
}
}
當使用帶有 forward: 字首 URL 的重試過濾器時,目標端點應仔細編寫,以便在發生錯誤時,它不會執行任何可能導致響應傳送到客戶端並提交的操作。例如,如果目標端點是一個帶註解的控制器,則目標控制器方法不應返回帶有錯誤狀態碼的 ResponseEntity。相反,它應該丟擲 Exception 或發出錯誤訊號(例如,透過 Mono.error(ex) 返回值),重試過濾器可以配置為透過重試來處理此錯誤。 |
| 當使用重試過濾器時,它將重試其之後的所有過濾器。請確保重試過濾器之後的過濾器在多次執行時其結果符合預期。 |
當使用重試過濾器與任何帶有請求體且 cacheBody=true 的 HTTP 方法時,請求體將被快取,閘道器將受到記憶體限制。請求體快取在由 MvcUtils.CACHED_REQUEST_BODY_ATT 定義的請求屬性中。物件的型別為 ByteArrayInputStream。 |
可以使用單個 status 和 method 新增簡化的“快捷方式”表示法。
以下兩個示例路由是等效的:
application.yml
spring:
cloud:
gateway:
mvc:
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