FallbackHeaders Filter
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: http://localhost:9994
predicates:
- Path=/fallback
filters:
- name: FallbackHeaders
args:
executionExceptionTypeHeaderName: Test-Header
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.CircuitBreakerFilterFunctions.circuitBreaker;
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.fallbackHeaders;
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("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 Filter section。