Retry 過濾器

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, TimeoutExceptionRetryException

  • 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 的重試過濾器時,請求體將被快取,閘道器將受到記憶體限制。請求體快取在由 MvcUtils.CACHED_REQUEST_BODY_ATT 定義的請求屬性中。該物件的型別是 ByteArrayInputStream

可以使用單個 statusmethod 新增簡化的“快捷方式”表示法。

以下兩個示例路由是等效的

application.yml
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