参考:官方文档
Spring Cloud
版本:Hoxton.SR5
Spring Cloud Gateway
版本:2.2.3.RELEASE
1 简介
Filter
可以以某种方式修改请求或者响应。Spring Cloud Gateway
提供了很多内置的GatewayFilterFactory
。这些filter
只对配置的当前route
有效。
2 内置的Filter
2.1 AddRequestHeaderGatewayFilterFactory
AddRequestHeaderGatewayFilterFactory
能够给请求添加Header
内容。它接受两个参数,一个是Header
中的属性名name
,一个是属性值value
。
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: https://example.org
filters:
- AddRequestHeader=X-Request-color, blue
如上配置,将会为请求添加X-Request-color:blue
的头部信息。
2.2 AddRequestParameterGatewayFilterFactory
AddRequestParameterGatewayFilterFactory
能够为请求添加参数。它接受两个参数,一个是参数的名name
,一个是参数的值value
。
spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: https://example.org
filters:
- AddRequestParameter=color, red
如上配置,将会为请求添加请求参数color=red
。
2.3 AddResponseHeaderGatewayFilterFactory
AddResponseHeaderGatewayFilterFactory
将会为响应添加Header
内容。它接受两个参数,一个是Header
中的属性名name
,一个是属性值value
。
spring:
cloud:
gateway:
routes:
- id: add_response_header_route
uri: https://example.org
filters:
- AddResponseHeader=X-Response-color, Blue
如上配置,将会为响应添加X-Response-color:Blue
的头部信息。
2.4 DedupeResponseHeaderGatewayFilterFactory
DedupeResponseHeaderGatewayFilterFactory
可以剔除响应头中的重读值。它接受两个参数,一个是name
参数,一个是可选的策略strategy
参数。name
参数可以填写多个值,用空格隔开,表示要剔除的Header
中的属性名。
spring:
cloud:
gateway:
routes:
- id: dedupe_response_header_route
uri: https://example.org
filters:
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
如上配置将会剔除响应头中的Access-Control-Allow-Credentials
和Access-Control-Allow-Origin
。
策略strategy
有三种选择:
RETAIN_FIRST
:保留第一个值,默认策略。RETAIN_LAST
:保留最后一个值。RETAIN_UNIQUE
:保留所有唯一值,以它们第一次出现的顺序保留。
2.5 HystrixGatewayFilterFactory
Netflix
已经将Hystrix
进入维护模式,官方建议使用SpringCloudCircuitBreakerFilterFactory
。
2.6 SpringCloudCircuitBreakerFilterFactory
SpringCloudCircuitBreakerFilterFactory
使用Spring Cloud CircuitBreaker APIs
将网关路由封装在熔断器中。
Spring Cloud CircuitBreaker
支持在Spring Cloud Gateway
中使用两种熔断器库,Hystrix
和Resilience4J
。因为Hystrix
已经进入维护阶段,所以官方建议使用Resilience4J
。
如果要使用SpringCloudCircuitBreakerFilterFactory
,需要在项目中引入熔断器的依赖spring-cloud-starter-circuitbreaker-reactor-resilience4j
或者spring-cloud-starter-netflix-hystrix
。
下面展示了如何配置这个filter
:
spring:
cloud:
gateway:
routes:
- id: circuitbreaker_route
uri: https://example.org
filters:
- CircuitBreaker=myCircuitBreaker
如上,配置了一个熔断器。关于如何设置熔断器策略,可以查看文档:
并且,可以配置一个fallbackUri
,当发生熔断的时候将会跳转这个地址。
spring:
cloud:
gateway:
routes:
- id: circuitbreaker_route
uri: https://example.org
filters:
- name: CircuitBreaker
args:
name: myCircuitBreaker
fallbackUri: forward:/inCaseOfFailureUseThis
- RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint
2.7 FallbackHeadersGatewayFilterFactory
FallbackHeadersGatewayFilterFactory
可以在转发请求到fallbackUri
的时候,为请求添加一个Header
,这个Header的值为具体的异常信息。
spring:
cloud:
gateway:
routes:
- id: ingredients
uri: lb://ingredients
predicates:
- Path=//ingredients/**
filters:
- name: Hystrix
args:
name: fetchIngredients
fallbackUri: forward:/fallback
- id: ingredients-fallback
uri: http://localhost:9994
predicates:
- Path=/fallback
filters:
- name: FallbackHeaders
args:
executionExceptionTypeHeaderName: Test-Header
2.8 MapRequestHeaderGatewayFilterFactory
MapRequestHeaderGatewayFilterFactory
能够转换请求头的内容。它接受两个参数,一个是原请求头fromHeader
,一个是转换后的请求头toHeader
。如果原请求头不存在,这个过滤器将不起作用。如果转换后的请求头已经存在,它的值将会用新的值。
spring:
cloud:
gateway:
routes:
- id: map_request_header_route
uri: https://example.org
filters:
- MapRequestHeader=X-Request-color, X-Request-newcolor
上面的配置,将会获取原请求头X-Request-color
的内容,并转换为新的请求头X-Request-newcolor
。
2.9 PrefixPathGatewayFilterFactory
PrefixPathGatewayFilterFactory
将会为请求的path
添加前缀。
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: https://example.org
filters:
- PrefixPath=/mypath
如上配置,将会为请求添加/mypath
前缀。例如,/hello
请求将会路由到/mypath/hello
。
2.10 PreserveHostHeaderGatewayFilterFactory
PreserveHostHeaderGatewayFilterFactory
不接受参数。如果不设置,那么名为 Host
的Header
由Http Client
控制;如果设置了,那么会设置一个请求属性(preserveHostHeader=true
),路由过滤器会检查从而去判断是否要发送原始的、名为Host
的Header
。
spring:
cloud:
gateway:
routes:
- id: preserve_host_route
uri: https://example.org
filters:
- PreserveHostHeader
2.11 RequestRateLimiterGatewayFilterFactory
RequestRateLimiterGatewayFilterFactory
可以对请求进行限流。它使用RateLimiter
的实现来判断当前请求是否可以通过,如果被限流了,默认将会返回HTTP 429 - Too Many Requests
。
详细内容,可以查看RequestRateLimiterGatewayFilterFactory
2.12 RedirectToGatewayFilterFactory
RedirectToGatewayFilterFactory
能够重定向请求。它接受两个参数,一个是状态status
,一个是url
。status
的值应该是300
系列的HTTP
状态码,例如301
。url
应该是一个有效的地址,它是Header
中Location
属性的值。
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: https://example.org
filters:
- RedirectTo=302, https://acme.org
如上配置,将会发送302
状态码,并携带Location:https://acme.org
的请求头信息。
2.13 RemoveRequestHeaderGatewayFilterFactory
RemoveRequestHeaderGatewayFilterFactory
可以移除请求头中的信息。它接受一个name
参数,表示将要移除的头部中的信息名称。
spring:
cloud:
gateway:
routes:
- id: removerequestheader_route
uri: https://example.org
filters:
- RemoveRequestHeader=X-Request-Foo
如上配置,将会移除请求头中X-Request-Foo
信息。
2.14 RemoveRequestParameterGatewayFilterFactory
RemoveRequestParameterGatewayFilterFactory
能够移除请求参数。它接受一个name
参数,表示将要移除的请求参数名称。
spring:
cloud:
gateway:
routes:
- id: removerequestparameter_route
uri: https://example.org
filters:
- RemoveRequestParameter=color
如上配置,将会移除请求中的color
参数。
2.15 RemoveResponseHeaderGatewayFilterFactory
RemoveResponseHeaderGatewayFilterFactory
能够移除响应头中的信息。它接受一个name
参数,表示将要移除的响应头中的信息名称。
spring:
cloud:
gateway:
routes:
- id: removeresponseheader_route
uri: https://example.org
filters:
- RemoveResponseHeader=X-Response-Foo
如上配置,将会移除响应头中的X-Response-Foo
信息。
2.16 RewritePathGatewayFilterFactory
RewritePathGatewayFilterFactory
能够重写请求路径。它接受一个描述path
的正则表达式,和一个替换表达式。
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: https://example.org
predicates:
- Path=/red/**
filters:
- RewritePath=/red(?<segment>/?.*), $\{segment}
如上配置,如果请求是/red/blue
,那么重写的后的路径是/blue
,注意由于YAML
规范,要用$\
替换为$
。
2.17 RewriteLocationResponseHeaderGatewayFilterFactory
RewriteLocationResponseHeaderGatewayFilterFactory
能够修改响应头中的Location
属性的值。它接受stripVersion
、locationHeaderName
、hostValue
、protocols
参数。
spring:
cloud:
gateway:
routes:
- id: rewritelocationresponseheader_route
uri: http://example.org
filters:
- RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,
stripVersion
可选三个值:
NEVER_STRIP
:即使原始请求路径不包含版本,版本也不会被删除。AS_IN_REQUEST
:(默认值),只有当原始请求路径不包含版本时,版本才会被删除。ALWAYS_STRIP
:即使原始请求路径包含版本,版本也总是被删除。
hostValue
如果指定了,将会替换响应头中Location
中的host:port
部分。
protocols
部分必须是一个有效的表示请求协议的正则表达式。默认值是http|https|ftp|ftps
。
2.18 RewriteResponseHeaderGatewayFilterFactory
RewriteResponseHeaderGatewayFilterFactory
能够重写响应头中的属性。它接受三个参数,name
表示响应头中的属性名,regexp
表示一个正则表达式,用来匹配name
对应的值,replacement
表示匹配之后重写的值。
spring:
cloud:
gateway:
routes:
- id: rewriteresponseheader_route
uri: https://example.org
filters:
- RewriteResponseHeader=X-Response-Red, , password=[^&]+, password=***
如上配置,假设响应头中X-Response-Red
属性的值为/42?user=ford&password=omg!what&flag=true
,将会被替换成/42?user=ford&password=***&flag=true
,其中password
的部分被替换了。
2.19 SaveSessionGatewayFilterFactory
SaveSessionGatewayFilterFactory
能够强制执行WebSession::save
操作。当使用Spring Session
与懒加载数据存储之类的东西时,这是特别有用的,并且需要确保在转发调用之前已保存会话状态。
spring:
cloud:
gateway:
routes:
- id: save_session
uri: https://example.org
predicates:
- Path=/foo/**
filters:
- SaveSession
如果要将Spring Security
与Spring Session
集成,并且希望确保将安全性详细信息转发到远程进程,则这很关键。
2.20 SecureHeadersGatewayFilterFactory
SecureHeadersGatewayFilterFactory
会给响应头加上如下内容:
X-Xss-Protection:1; mode=block
Strict-Transport-Security:max-age=631138519
X-Frame-Options:DENY
X-Content-Type-Options:nosniff
Referrer-Policy:no-referrer
Content-Security-Policy:default-src 'self' https:; font-src 'self' https: data:; img-src 'self' https: data:; object-src 'none'; script-src https:; style-src 'self' https: 'unsafe-inline'
X-Download-Options:noopen
X-Permitted-Cross-Domain-Policies:none
要更改默认值,请在spring.cloud.gateway.filter.secure-headers
命名空间中设置相应的属性:
xss-protection-header
strict-transport-security
frame-options
content-type-options
referrer-policy
content-security-policy
download-options
permitted-cross-domain-policies
禁用这些属性,可以通过spring.cloud.gateway.filter.secure-headers.disable
来设置:
spring.cloud.gateway.filter.secure-headers.disable=x-frame-options,strict-transport-security
2.21 SetPathGatewayFilterFactory
SetPathGatewayFilterFactory
采用路径模板参数template
。 它提供了一种通过允许模板化路径段来操作请求路径的简单方法, 这使用了Spring Framework
中的uri
模板,允许多个匹配的段。
spring:
cloud:
gateway:
routes:
- id: setpath_route
uri: https://example.org
predicates:
- Path=/red/{segment}
filters:
- SetPath=/{segment}
如上配置,如果请求路径是/red/blue
,路径将会被设置为/blue
。
2.22 SetRequestHeaderGatewayFilterFactory
SetRequestHeaderGatewayFilterFactory
能够设置请求头。它接受两个参数,一个是属性名name
,一个是属性值value
。
spring:
cloud:
gateway:
routes:
- id: setrequestheader_route
uri: https://example.org
filters:
- SetRequestHeader=X-Request-Color, Blue
这个filter
能够根据name
替换请求头中的value
,注意不是添加一个header
属性。
这个filter
的配置中也可以使用URI
变量,形如{value}
。如下:
spring:
cloud:
gateway:
routes:
- id: setrequestheader_route
uri: https://example.org
predicates:
- Host: {segment}.myhost.org
filters:
- SetRequestHeader=foo, bar-{segment}
2.23 SetResponseHeaderGatewayFilterFactory
SetResponseHeaderGatewayFilterFactory
能够设置响应头。它接受两个参数,一个是属性名name
,一个是属性值value
。
spring:
cloud:
gateway:
routes:
- id: setresponseheader_route
uri: https://example.org
filters:
- SetResponseHeader=X-Request-Color, Blue
这个filter
能够根据name
替换响应头中的value
,注意不是添加一个header
属性。
这个filter
的配置中也可以使用URI
变量,形如{value}
。如下:
spring:
cloud:
gateway:
routes:
- id: setresponseheader_route
uri: https://example.org
predicates:
- Host: {segment}.myhost.org
filters:
- SetResponseHeader=foo, bar-{segment}
2.24 SetStatusGatewayFilterFactory
SetStatusGatewayFilterFactory
能够设置HTTP
状态码。它接受一个status
值,必须是Spring
中的HttpStatus
中的有效值,可以是数字,也可以是字符串。
spring:
cloud:
gateway:
routes:
- id: setstatusstring_route
uri: https://example.org
filters:
- SetStatus=BAD_REQUEST
- id: setstatusint_route
uri: https://example.org
filters:
- SetStatus=401
2.25 StripPrefixGatewayFilterFactory
StripPrefixGatewayFilterFactory
可以对请求路径进行处理,根据传入的参数parts
值,剥离路径个数。
spring:
cloud:
gateway:
routes:
- id: nameRoot
uri: https://nameservice
predicates:
- Path=/name/**
filters:
- StripPrefix=2
例如上述配置,如果请求的url
是https://nameservice/name/blue/red
,那么请求的路径path
则是/name/blue/red
,根据配置
StripPrefix=2
需要剥离请求中的路径个数为2
,也就是删除name/blue
,则最终请求的url
变为https://nameservice/red
。
2.26 RetryGatewayFilterFactory
RetryGatewayFilterFactory
能够在转发请求到下游不通的时候,进行重试。
它接受如下参数:
retries
:应该尝试的重试次数。statuses
:指定出现哪些HTTP
状态码的时候需要重试,取值org.springframework.http.HttpStatus
。methods
:指定针对哪些HTTP
请求方法需要重试,取值org.springframework.http.HttpMethod
。series
:用来指定出现哪些类的HTTP
状态码需要重试,取值org.springframework.http.HttpStatus.Series
。exceptions
:用来指定出现哪些异常的时候需要重试。backoff
:
默认情况下,取值:
retries
:3
次。series
:5XX
系列的状态码。methods
:GET
请求。exceptions
:IOException
和TimeoutException
。backoff
:disabled
spring:
cloud:
gateway:
routes:
- id: retry_test
uri: http://localhost:8080/flakey
predicates:
- Host=*.retry.com
filters:
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY
methods: GET,POST
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor: 2
basedOnPreviousValue: false
2.27 RequestSizeGatewayFilterFactory
RequestSizeGatewayFilterFactory
可以对请求大小进行限制,当请求的大小大于这个filter
设置的限制值的时候,filter
会拦截请求,不转发到下游服务器。
它接受一个maxSize
参数,用来限制请求内容的最大值,单位为Byte
。
spring:
cloud:
gateway:
routes:
- id: request_size_route
uri: http://localhost:8080/upload
predicates:
- Path=/upload
filters:
- name: RequestSize
args:
maxSize: 5000000
请求大小超过最大值,filter
将会返回一个413 Payload Too Large
的状态码信息,并在header
中附带一个errorMessage
信息。例如:
errorMessage : Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB
如果不指定最大值,默认是5MB
。
2.28 SetRequestHostHeaderGatewayFilterFactory
SetRequestHostHeaderGatewayFilterFactory
能够修改Header
中的host
信息。
spring:
cloud:
gateway:
routes:
- id: set_request_host_header_route
uri: http://localhost:8080/headers
predicates:
- Path=/headers
filters:
- name: SetRequestHost
args:
host: example.org
2.29 DefaultFilters
如果想要添加一批filter
并对所有route
有效,可以使用spring.cloud.gateway.default-filters
。它接受一个filter
列表。
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Red, Default-Blue
- PrefixPath=/httpbin