Retry 篩選器

Retry 篩選器支援下列參數

  • retries:應嘗試的重試次數。

  • methods:應重試的 HTTP 方法,以 org.springframework.http.HttpMethod 表示。

  • series:應重試的狀態碼系列,以 org.springframework.http.HttpStatus.Series 表示。

  • exceptions:應重試的已擲出例外清單。

如果啟用 Retry 篩選器,則會設定下列預設值

  • retries:三次

  • series:5XX 系列

  • methods:GET 方法

  • exceptionsIOExceptionTimeoutExceptionRetryException

下列清單設定了重試篩選器

application.yml
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
GatewaySampleApplication.java
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) 傳回值),您可以設定重試篩選器來處理這些錯誤並進行重試。

可以使用單一 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