本文基于Spring Cloud Greenwich SR2
內(nèi)置的過濾器工廠
這里簡單將Spring Cloud Gateway內(nèi)置的所有過濾器工廠整理成了一張表格,雖然不是很詳細美旧,但能作為速覽使用鼎文。如下:
過濾器工廠 | 作用 | 參數(shù) |
---|---|---|
AddRequestHeader | 為原始請求添加Header | Header的名稱及值 |
AddRequestParameter | 為原始請求添加請求參數(shù) | 參數(shù)名稱及值 |
AddResponseHeader | 為原始響應(yīng)添加Header | Header的名稱及值 |
DedupeResponseHeader | 剔除響應(yīng)頭中重復(fù)的值 | 需要去重的Header名稱及去重策略 |
Hystrix | 為路由引入Hystrix的斷路器保護 |
HystrixCommand 的名稱 |
FallbackHeaders | 為fallbackUri的請求頭中添加具體的異常信息 | Header的名稱 |
PrefixPath | 為原始請求路徑添加前綴 | 前綴路徑 |
PreserveHostHeader | 為請求添加一個preserveHostHeader=true的屬性渔肩,路由過濾器會檢查該屬性以決定是否要發(fā)送原始的Host | 無 |
RequestRateLimiter | 用于對請求限流,限流算法為令牌桶 | keyResolver拇惋、rateLimiter周偎、statusCode抹剩、denyEmptyKey、emptyKeyStatus |
RedirectTo | 將原始請求重定向到指定的URL | http狀態(tài)碼及重定向的url |
RemoveHopByHopHeadersFilter | 為原始請求刪除IETF組織規(guī)定的一系列Header | 默認(rèn)就會啟用蓉坎,可以通過配置指定僅刪除哪些Header |
RemoveRequestHeader | 為原始請求刪除某個Header | Header名稱 |
RemoveResponseHeader | 為原始響應(yīng)刪除某個Header | Header名稱 |
RewritePath | 重寫原始的請求路徑 | 原始路徑正則表達式以及重寫后路徑的正則表達式 |
RewriteResponseHeader | 重寫原始響應(yīng)中的某個Header | Header名稱澳眷,值的正則表達式,重寫后的值 |
SaveSession | 在轉(zhuǎn)發(fā)請求之前蛉艾,強制執(zhí)行WebSession::save 操作 |
無 |
secureHeaders | 為原始響應(yīng)添加一系列起安全作用的響應(yīng)頭 | 無钳踊,支持修改這些安全響應(yīng)頭的值 |
SetPath | 修改原始的請求路徑 | 修改后的路徑 |
SetResponseHeader | 修改原始響應(yīng)中某個Header的值 | Header名稱,修改后的值 |
SetStatus | 修改原始響應(yīng)的狀態(tài)碼 | HTTP 狀態(tài)碼勿侯,可以是數(shù)字拓瞪,也可以是字符串 |
StripPrefix | 用于截斷原始請求的路徑 | 使用數(shù)字表示要截斷的路徑的數(shù)量 |
Retry | 針對不同的響應(yīng)進行重試 | retries、statuses助琐、methods祭埂、series |
RequestSize | 設(shè)置允許接收最大請求包的大小。如果請求包大小超過設(shè)置的值弓柱,則返回 413 Payload Too Large
|
請求包大小沟堡,單位為字節(jié),默認(rèn)值為5M |
ModifyRequestBody | 在轉(zhuǎn)發(fā)請求之前修改原始請求體內(nèi)容 | 修改后的請求體內(nèi)容 |
ModifyResponseBody | 修改原始響應(yīng)體的內(nèi)容 | 修改后的響應(yīng)體內(nèi)容 |
Default | 為所有路由添加過濾器 | 過濾器工廠名稱及值 |
Tips:每個過濾器工廠都對應(yīng)一個實現(xiàn)類矢空,并且這些類的名稱必須以GatewayFilterFactory
結(jié)尾航罗,這是Spring Cloud Gateway的一個約定,例如AddRequestHeader
對應(yīng)的實現(xiàn)類為AddRequestHeaderGatewayFilterFactory
屁药。對源碼感興趣的小伙伴就可以按照這個規(guī)律拼接出具體的類名粥血,以此查找這些內(nèi)置過濾器工廠的實現(xiàn)代碼
1、AddRequestHeader GatewayFilter Factory
為原始請求添加Header酿箭,配置示例:
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: https://example.org
filters:
- AddRequestHeader=X-Request-Foo, Bar
為原始請求添加名為 X-Request-Foo
复亏,值為 Bar
的請求頭
2、AddRequestParameter GatewayFilter Factory
為原始請求添加請求參數(shù)及值缭嫡,配置示例:
spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: https://example.org
filters:
- AddRequestParameter=foo, bar
為原始請求添加名為foo缔御,值為bar的參數(shù),即:foo=bar
3妇蛀、AddResponseHeader GatewayFilter Factory
為原始響應(yīng)添加Header耕突,配置示例:
spring:
cloud:
gateway:
routes:
- id: add_response_header_route
uri: https://example.org
filters:
- AddResponseHeader=X-Response-Foo, Bar
為原始響應(yīng)添加名為 X-Request-Foo
,值為 Bar
的響應(yīng)頭
4评架、DedupeResponseHeader GatewayFilter Factory
DedupeResponseHeader可以根據(jù)配置的Header名稱及去重策略剔除響應(yīng)頭中重復(fù)的值眷茁,這是Spring Cloud Greenwich SR2提供的新特性,低于這個版本無法使用纵诞。
我們在Gateway以及微服務(wù)上都設(shè)置了CORS(解決跨域)Header的話上祈,如果不做任何配置,那么請求 -> 網(wǎng)關(guān) -> 微服務(wù),獲得的CORS Header的值登刺,就將會是這樣的:
Access-Control-Allow-Credentials: true, true
Access-Control-Allow-Origin: https://musk.mars, https://musk.mars
可以看到這兩個Header的值都重復(fù)了籽腕,若想把這兩個Header的值去重的話,就需要使用到DedupeResponseHeader塘砸,配置示例:
spring:
cloud:
gateway:
routes:
- id: dedupe_response_header_route
uri: https://example.org
filters:
# 若需要去重的Header有多個节仿,使用空格分隔
- DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
去重策略:
- RETAIN_FIRST:默認(rèn)值晤锥,保留第一個值
- RETAIN_LAST:保留最后一個值
- RETAIN_UNIQUE:保留所有唯一值掉蔬,以它們第一次出現(xiàn)的順序保留
若想對該過濾器工廠有個比較全面的了解的話,建議閱讀該過濾器工廠的源碼矾瘾,因為源碼里有詳細的注釋及示例女轿,比官方文檔寫得還好:org.springframework.cloud.gateway.filter.factory.DedupeResponseHeaderGatewayFilterFactory
5、Hystrix GatewayFilter Factory
為路由引入Hystrix的斷路器保護壕翩,配置示例:
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: https://example.org
filters:
- Hystrix=myCommandName
Hystrix是Spring Cloud第一代容錯組件蛉迹,不過已經(jīng)進入維護模式,未來Hystrix會被Spring Cloud移除掉放妈,取而代之的是Alibaba Sentinel/Resilience4J北救。所以本文不做詳細介紹了,感興趣的話可以參考官方文檔:
6芜抒、FallbackHeaders GatewayFilter Factory
同樣是對Hystrix的支持珍策,上一小節(jié)所介紹的過濾器工廠支持一個配置參數(shù):fallbackUri
,該配置用于當(dāng)發(fā)生異常時將請求轉(zhuǎn)發(fā)到一個特定的uri上宅倒。而FallbackHeaders
這個過濾工廠可以在轉(zhuǎn)發(fā)請求到該uri時添加一個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
這里也不做詳細介紹了拐迁,感興趣可以參考官方文檔:
7蹭劈、PrefixPath GatewayFilter Factory
為原始的請求路徑添加一個前綴路徑,配置示例:
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: https://example.org
filters:
- PrefixPath=/mypath
該配置使訪問${GATEWAY_URL}/hello
會轉(zhuǎn)發(fā)到https://example.org/mypath/hello
8线召、PreserveHostHeader GatewayFilter Factory
為請求添加一個preserveHostHeader=true的屬性铺韧,路由過濾器會檢查該屬性以決定是否要發(fā)送原始的Host Header。配置示例:
spring:
cloud:
gateway:
routes:
- id: preserve_host_route
uri: https://example.org
filters:
- PreserveHostHeader
如果不設(shè)置缓淹,那么名為 Host
的Header將由Http Client控制
9哈打、RequestRateLimiter GatewayFilter Factory
用于對請求進行限流,限流算法為令牌桶割卖。配置示例:
spring:
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: https://example.org
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
由于另一篇文章中已經(jīng)介紹過如何使用該過濾器工廠實現(xiàn)網(wǎng)關(guān)限流前酿,所以這里就不再贅述了:
或者參考官方文檔:
10、RedirectTo GatewayFilter Factory
將原始請求重定向到指定的Url鹏溯,配置示例:
spring:
cloud:
gateway:
routes:
- id: redirect_route
uri: https://example.org
filters:
- RedirectTo=302, https://acme.org
該配置使訪問 ${GATEWAY_URL}/hello
會被重定向到 https://acme.org/hello
罢维,并且攜帶一個 Location:http://acme.org
的Header,而返回客戶端的HTTP狀態(tài)碼為302
注意事項:
- HTTP狀態(tài)碼應(yīng)為3xx,例如301
- URL必須是合法的URL肺孵,該URL會作為
Location
Header的值
11匀借、RemoveHopByHopHeadersFilter GatewayFilter Factory
為原始請求刪除IETF組織規(guī)定的一系列Header,默認(rèn)刪除的Header如下:
- Connection
- Keep-Alive
- Proxy-Authenticate
- Proxy-Authorization
- TE
- Trailer
- Transfer-Encoding
- Upgrade
可以通過配置去指定僅刪除哪些Header平窘,配置示例:
spring:
cloud:
gateway:
filter:
remove-hop-by-hop:
# 多個Header使用逗號(,)分隔
headers: Connection,Keep-Alive
12吓肋、RemoveRequestHeader GatewayFilter Factory
為原始請求刪除某個Header,配置示例:
spring:
cloud:
gateway:
routes:
- id: removerequestheader_route
uri: https://example.org
filters:
- RemoveRequestHeader=X-Request-Foo
刪除原始請求中名為 X-Request-Foo
的請求頭
13瑰艘、RemoveResponseHeader GatewayFilter Factory
為原始響應(yīng)刪除某個Header是鬼,配置示例:
spring:
cloud:
gateway:
routes:
- id: removeresponseheader_route
uri: https://example.org
filters:
- RemoveResponseHeader=X-Response-Foo
刪除原始響應(yīng)中名為 X-Request-Foo
的響應(yīng)頭
14、RewritePath GatewayFilter Factory
通過正則表達式重寫原始的請求路徑紫新,配置示例:
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: https://example.org
predicates:
- Path=/foo/**
filters:
# 參數(shù)1為原始路徑的正則表達式均蜜,參數(shù)2為重寫后路徑的正則表達式
- RewritePath=/foo/(?<segment>.*), /$\{segment}
該配置使得訪問 /foo/bar
時,會將路徑重寫為/bar
再進行轉(zhuǎn)發(fā)芒率,也就是會轉(zhuǎn)發(fā)到 https://example.org/bar
囤耳。需要注意的是:由于YAML語法,需用$\
替換 $
15偶芍、RewriteResponseHeader GatewayFilter Factory
重寫原始響應(yīng)中的某個Header充择,配置示例:
spring:
cloud:
gateway:
routes:
- id: rewriteresponseheader_route
uri: https://example.org
filters:
# 參數(shù)1為Header名稱,參數(shù)2為值的正則表達式匪蟀,參數(shù)3為重寫后的值
- RewriteResponseHeader=X-Response-Foo, password=[^&]+, password=***
該配置的意義在于:如果響應(yīng)頭中 X-Response-Foo
的值為/42?user=ford&password=omg!what&flag=true
椎麦,那么就會被按照配置的值重寫成/42?user=ford&password=***&flag=true
,也就是把其中的password=omg!what
重寫成了password=***
16萄窜、SaveSession GatewayFilter Factory
在轉(zhuǎn)發(fā)請求之前铃剔,強制執(zhí)行WebSession::save
操作,配置示例:
spring:
cloud:
gateway:
routes:
- id: save_session
uri: https://example.org
predicates:
- Path=/foo/**
filters:
- SaveSession
主要用在那種像 Spring Session 延遲數(shù)據(jù)存儲(數(shù)據(jù)不是立刻持久化)的查刻,并希望在請求轉(zhuǎn)發(fā)前確保session狀態(tài)保存情況键兜。如果你將Spring Secutiry于Spring Session集成使用,并想確保安全信息都傳到下游機器穗泵,你就需要配置這個filter普气。
17、secureHeaders GatewayFilter Factory
secureHeaders過濾器工廠主要是參考了這篇博客中的建議佃延,為原始響應(yīng)添加了一系列起安全作用的響應(yīng)頭现诀。默認(rèn)會添加如下Headers(包括值):
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
如果你想修改這些Header的值,那么就需要使用這些Headers對應(yīng)的后綴履肃,如下:
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:
# 修改 X-Xss-Protection 的值為 2; mode=unblock
xss-protection-header: 2; mode=unblock
如果想禁用某些Header仔沿,可使用如下配置:
spring:
cloud:
gateway:
filter:
secure-headers:
# 多個使用逗號(,)分隔
disable: frame-options,download-options
18、SetPath GatewayFilter Factory
修改原始的請求路徑尺棋,配置示例:
spring:
cloud:
gateway:
routes:
- id: setpath_route
uri: https://example.org
predicates:
- Path=/foo/{segment}
filters:
- SetPath=/{segment}
該配置使訪問 ${GATEWAY_URL}/foo/bar
時會轉(zhuǎn)發(fā)到 https://example.org/bar
封锉,也就是原本的/foo/bar
被修改為了/bar
19、SetResponseHeader GatewayFilter Factory
修改原始響應(yīng)中某個Header的值,配置示例:
spring:
cloud:
gateway:
routes:
- id: setresponseheader_route
uri: https://example.org
filters:
- SetResponseHeader=X-Response-Foo, Bar
將原始響應(yīng)中 X-Response-Foo
的值修改為 Bar
20成福、SetStatus GatewayFilter Factory
修改原始響應(yīng)的狀態(tài)碼碾局,配置示例:
spring:
cloud:
gateway:
routes:
- id: setstatusstring_route
uri: https://example.org
filters:
# 字符串形式
- SetStatus=BAD_REQUEST
- id: setstatusint_route
uri: https://example.org
filters:
# 數(shù)字形式
- SetStatus=401
SetStatusd的值可以是數(shù)字,也可以是字符串奴艾。但一定要是Spring HttpStatus
枚舉類中的值净当。上面這兩種配置都可以返回401這個HTTP狀態(tài)碼。
21蕴潦、StripPrefix GatewayFilter Factory
用于截斷原始請求的路徑像啼,配置示例:
spring:
cloud:
gateway:
routes:
- id: nameRoot
uri: http://nameservice
predicates:
- Path=/name/**
filters:
# 數(shù)字表示要截斷的路徑的數(shù)量
- StripPrefix=2
如上配置,如果請求的路徑為 /name/bar/foo
品擎,那么則會截斷成/foo
后進行轉(zhuǎn)發(fā) 埋合,也就是會截斷2個路徑。
22萄传、Retry GatewayFilter Factory
針對不同的響應(yīng)進行重試,例如可以針對HTTP狀態(tài)碼進行重試蜜猾,配置示例:
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
可配置如下參數(shù):
-
retries
:重試次數(shù) -
statuses
:需要重試的狀態(tài)碼秀菱,取值在org.springframework.http.HttpStatus
中 -
methods
:需要重試的請求方法,取值在org.springframework.http.HttpMethod
中 -
series
:HTTP狀態(tài)碼序列蹭睡,取值在org.springframework.http.HttpStatus.Series
中
23衍菱、RequestSize GatewayFilter Factory
設(shè)置允許接收最大請求包的大小,配置示例:
spring:
cloud:
gateway:
routes:
- id: request_size_route
uri: http://localhost:8080/upload
predicates:
- Path=/upload
filters:
- name: RequestSize
args:
# 單位為字節(jié)
maxSize: 5000000
如果請求包大小超過設(shè)置的值肩豁,則會返回 413 Payload Too Large
以及一個errorMessage
24脊串、Modify Request Body GatewayFilter Factory
在轉(zhuǎn)發(fā)請求之前修改原始請求體內(nèi)容,該過濾器工廠只能通過代碼配置清钥,不支持在配置文件中配置琼锋。代碼示例:
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org")
.filters(f -> f.prefixPath("/httpbin")
.modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
(exchange, s) -> return Mono.just(new Hello(s.toUpperCase())))).uri(uri))
.build();
}
static class Hello {
String message;
public Hello() { }
public Hello(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
Tips:該過濾器工廠處于 BETA 狀態(tài),未來API可能會變化祟昭,生產(chǎn)環(huán)境請慎用
25缕坎、Modify Response Body GatewayFilter Factory
可用于修改原始響應(yīng)體的內(nèi)容,該過濾器工廠同樣只能通過代碼配置篡悟,不支持在配置文件中配置谜叹。代碼示例:
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
return builder.routes()
.route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
.filters(f -> f.prefixPath("/httpbin")
.modifyResponseBody(String.class, String.class,
(exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri)
.build();
}
Tips:該過濾器工廠處于 BETA 狀態(tài),未來API可能會變化搬葬,生產(chǎn)環(huán)境請慎用
26荷腊、Default Filters
Default Filters用于為所有路由添加過濾器工廠,也就是說通過Default Filter所配置的過濾器工廠會作用到所有的路由上急凰。配置示例:
spring:
cloud:
gateway:
default-filters:
- AddResponseHeader=X-Response-Default-Foo, Default-Bar
- PrefixPath=/httpbin
官方文檔: