FallbackHeaders 過濾器
FallbackHeaders 工廠允許您在轉發到外部應用程式中 fallbackUri 的請求的頭部中新增 Spring Cloud CircuitBreaker 執行異常詳細資訊,如以下場景所示:
application.yml
spring:
cloud:
gateway:
mvc:
routes:
- id: ingredients
uri: lb://ingredients
predicates:
- Path=/ingredients/**
filters:
- name: CircuitBreaker
args:
name: fetchIngredients
fallbackUri: forward:/fallback
- id: ingredients-fallback
uri: https://: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("https://: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 過濾器部分。