FallbackHeaders フィルター

FallbackHeaders ファクトリでは、次のシナリオのように、外部アプリケーションの fallbackUri に転送されるリクエストのヘッダーに Spring Cloud CircuitBreaker 実行例外の詳細を追加できます。

application.yml
spring:
  cloud:
    gateway:
      server:
        webmvc:
          routes:
            - id: ingredients
              uri: lb://ingredients
              predicates:
              - Path=/ingredients/**
              filters:
              - name: CircuitBreaker
                args:
                  name: fetchIngredients
                  fallbackUri: forward:/fallback
            - id: ingredients-fallback
              uri: http://localhost:9994
              predicates:
              - Path=/fallback
              filters:
              - name: FallbackHeaders
                args:
                  executionExceptionTypeHeaderName: Test-Header
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.fallbackHeaders;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.uri;
import static org.springframework.cloud.gateway.server.mvc.filter.CircuitBreakerFilterFunctions.circuitBreaker;
import static org.springframework.cloud.gateway.server.mvc.filter.LoadBalancerFilterFunctions.lb;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsCircuitBreakerFallbackToGatewayRoute() {
        return route("ingredients")
                .route(path("/ingredients/**"), http())
                .filter(lb("ingredients"))
                .filter(circuitBreaker("fetchIngredients", URI.create("forward:/fallback")))
                .build()
            .and(route("ingredients-fallback")
                .route(path("/fallback"), http())
                .before(uri("http://localhost:9994"))
                .before(fallbackHeaders())
                .build());
    }
}

この例では、サーキットブレーカーの実行中に実行例外が発生した後、リクエストは localhost:9994 で実行されているアプリケーションの fallback エンドポイントまたはハンドラーに転送されます。例外型、メッセージ、(利用可能な場合)根本原因の例外型とメッセージを含むヘッダーは、FallbackHeaders フィルターによってそのリクエストに追加されます。

次の引数の値を設定することにより、構成内のヘッダーの名前を上書きできます(デフォルト値で示されています)。

  • executionExceptionTypeHeaderName ("Execution-Exception-Type")

  • executionExceptionMessageHeaderName ("Execution-Exception-Message")

  • rootCauseExceptionTypeHeaderName ("Root-Cause-Exception-Type")

  • rootCauseExceptionMessageHeaderName ("Root-Cause-Exception-Message")

サーキットブレーカーとゲートウェイの詳細については、Spring Cloud CircuitBreaker フィルター部を参照してください。