FallbackHeaders
過濾器
FallbackHeaders
工廠允許您將 Spring Cloud CircuitBreaker 執行異常的詳細資訊新增到轉發到外部應用中 fallbackUri
的請求頭中,如下所示:
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 過濾器部分。