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: 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 过滤器部分。