AddRequestHeadersIfNotPresent
Filter
AddRequestHeadersIfNotPresent
过滤器使用冒号分隔的一组 name
和 value
对。以下示例配置了一个 AddRequestHeadersIfNotPresent
过滤器:
application.yml
spring:
cloud:
gateway:
mvc:
routes:
- id: add_request_headers_route
uri: https://example.org
filters:
- AddRequestHeadersIfNotPresent=X-Request-Color-1:blue,X-Request-Color-2:green
GatewaySampleApplication.java
import static org.springframework.cloud.gateway.server.mvc.filter.BeforeFilterFunctions.addRequestHeadersIfNotPresent;
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> gatewayRouterFunctionsAddReqHeader() {
return route(GET("/red"), http("https://example.org"))
.before(addRequestHeadersIfNotPresent("X-Request-Color-1:blue","X-Request-Color-2:green"));
}
}
这个清单为所有匹配请求将 2 个标头 X-Request-Color-1:blue
和 X-Request-Color-2:green
添加到下游请求标头中。这类似于 AddRequestHeader
的工作方式,但与 AddRequestHeader
不同,它仅在标头不存在时才会执行此操作。否则,将发送客户端请求中的原始值。
此外,要设置多值标头,需多次使用标头名称,例如 addRequestHeadersIfNotPresent("X-Request-Color-1:blue","X-Request-Color-1:green")
。
AddRequestHeadersIfNotPresent
还支持用于匹配路径或主机的 URI 变量。URI 变量可用于值,并会在运行时进行展开。以下示例配置了一个使用变量的 AddRequestHeadersIfNotPresent
过滤器:
GatewaySampleApplication.java
@Configuration
class RouteConfiguration {
@Bean
public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
return route(GET("/red/{segment}"), http("https://example.org"))
.before(addRequestHeadersIfNotPresent("X-Request-red", "blue-{segment}"));
}
}
application.yml
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: https://example.org
predicates:
- Path=/red/{segment}
filters:
- AddRequestHeadersIfNotPresent=X-Request-Red:Blue-{segment}