目錄
1. How to Include Spring Cloud Gateway
2. Glossary
3. How It Works
4. Route Predicate Factories
5. GatewayFilter Factories
6. Global Filters
7. TLS / SSL
8. Configuration
9. Reactor Netty Access Logs
10. CORS Configuration
11. Actuator API
12. Developer Guide
該項目提供了一個建立在Spring Ecosystem之上的API網(wǎng)關(guān),包括:Spring 5,Spring Boot 2和Project Reactor婆翔。Spring Cloud Gateway旨在提供一種簡單而有效的方式來對API進行路由姥宝,并為他們提供切面,例如:安全性其骄,監(jiān)控/指標(biāo) 和彈性等亏镰。
1. 如何在工程中引用Spring Cloud Gateway
要在項目中引入Spring Cloud Gateway,需要引用 group org.springframework.cloud
和 artifact id為spring-cloud-starter-gateway
starter拯爽。最新的Spring Cloud Release 構(gòu)建信息索抓,請參閱Spring Cloud Project page。
如果應(yīng)用了該starter毯炮,但由于某種原因不希望啟用網(wǎng)關(guān)逼肯,請進行設(shè)置spring.cloud.gateway.enabled=false
。
重要
Spring Cloud Gateway依賴Spring Boot和Spring Webflux提供的Netty runtime桃煎。它不能在傳統(tǒng)的Servlet容器中工作或構(gòu)建為WAR
2. 詞匯表
- Route 路由:gateway的基本構(gòu)建模塊篮幢。它由ID、目標(biāo)URI为迈、斷言集合和過濾器集合組成三椿。如果聚合斷言結(jié)果為真奈揍,則匹配到該路由。
-
Predicate 斷言:這是一個Java 8 Function Predicate赋续。輸入類型是 Spring Framework
ServerWebExchange
男翰。這允許開發(fā)人員可以匹配來自HTTP請求的任何內(nèi)容,例如Header或參數(shù)纽乱。 -
Filter 過濾器:這些是使用特定工廠構(gòu)建的 Spring Framework
GatewayFilter
實例蛾绎。所以可以在返回請求之前或之后修改請求和響應(yīng)的內(nèi)容。
3. 如何工作的
客戶端向Spring Cloud Gateway發(fā)出請求鸦列。如果Gateway Handler Mapping確定請求與路由匹配租冠,則將其發(fā)送到Gateway Web Handler。此handler通過特定于該請求的過濾器鏈處理請求薯嗤。圖中filters被虛線劃分的原因是filters可以在發(fā)送代理請求之前或之后執(zhí)行邏輯顽爹。先執(zhí)行所有“pre filter”邏輯,然后進行請求代理骆姐。在請求代理執(zhí)行完后镜粤,執(zhí)行“post filter”邏輯。
注意
HTTP和HTTPS URI默認(rèn)端口設(shè)置是80和443玻褪。
4. 路由斷言Factories
Spring Cloud Gateway將路由作為Spring WebFlux HandlerMapping
基礎(chǔ)結(jié)構(gòu)的一部分進行匹配肉渴。Spring Cloud Gateway包含許多內(nèi)置的路由斷言Factories。這些斷言都匹配HTTP請求的不同屬性带射。多個路由斷言Factories可以通過 and
組合使用同规。
4.1 After 路由斷言 Factory
After Route Predicate Factory采用一個參數(shù)——日期時間。在該日期時間之后發(fā)生的請求都將被匹配窟社。
application.yml
spring:
cloud:
gateway:
routes:
- id: after_route
uri: http://example.org
predicates:
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
4.2 Before 路由斷言 Factory
Before Route Predicate Factory采用一個參數(shù)——日期時間券勺。在該日期時間之前發(fā)生的請求都將被匹配。
application.yml.
spring:
cloud:
gateway:
routes:
- id: before_route
uri: http://example.org
predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
4.3 Between 路由斷言 Factory
Between 路由斷言 Factory有兩個參數(shù)灿里,datetime1和datetime2关炼。在datetime1和datetime2之間的請求將被匹配。datetime2參數(shù)的實際時間必須在datetime1之后钠四。
application.yml.
spring:
cloud:
gateway:
routes:
- id: between_route
uri: http://example.org
predicates:
- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
4.4 Cookie 路由斷言 Factory
Cookie 路由斷言 Factory有兩個參數(shù)盗扒,cookie名稱和正則表達式。請求包含次cookie名稱且正則表達式為真的將會被匹配缀去。
application.yml
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: http://example.org
predicates:
- Cookie=chocolate, ch.p
4.5 Header 路由斷言 Factory
Header 路由斷言 Factory有兩個參數(shù)侣灶,header名稱和正則表達式。請求包含次header名稱且正則表達式為真的將會被匹配缕碎。
application.yml.
spring:
cloud:
gateway:
routes:
- id: header_route
uri: http://example.org
predicates:
- Header=X-Request-Id, \d+
4.6 Host 路由斷言 Factory
Host 路由斷言 Factory包括一個參數(shù):host name列表褥影。使用Ant路徑匹配規(guī)則,.
作為分隔符咏雌。
application.yml.
spring:
cloud:
gateway:
routes:
- id: host_route
uri: http://example.org
predicates:
- Host=**.somehost.org,**.anotherhost.org
4.7 Method 路由斷言 Factory
Method 路由斷言 Factory只包含一個參數(shù): 需要匹配的HTTP請求方式
application.yml.
spring:
cloud:
gateway:
routes:
- id: method_route
uri: http://example.org
predicates:
- Method=GET
所有GET請求都將被路由
4.8 Path 路由斷言 Factory
Path 路由斷言 Factory 有2個參數(shù): 一個Spring PathMatcher
表達式列表和可選matchOptionalTrailingSeparator
標(biāo)識 .
application.yml.
spring:
cloud:
gateway:
routes:
- id: host_route
uri: http://example.org
predicates:
- Path=/foo/{segment},/bar/{segment}
例如: /foo/1
or /foo/bar
or /bar/baz
的請求都將被匹配
URI 模板變量 (如上例中的 segment
) 將以Map的方式保存于ServerWebExchange.getAttributes()
key為ServerWebExchangeUtils.URI_TEMPLATE_VARIABLES_ATTRIBUTE
. 這些值將在GatewayFilter Factories使用
可以使用以下方法來更方便地訪問這些變量凡怎。
Map<String, String> uriVariables = ServerWebExchangeUtils.getPathPredicateVariables(exchange);
String segment = uriVariables.get("segment");
4.9 Query 路由斷言 Factory
Query 路由斷言 Factory 有2個參數(shù): 必選項 param
和可選項 regexp
.
application.yml.
spring:
cloud:
gateway:
routes:
- id: query_route
uri: http://example.org
predicates:
- Query=baz
則包含了請求參數(shù) baz
的都將被匹配校焦。
application.yml.
spring:
cloud:
gateway:
routes:
- id: query_route
uri: http://example.org
predicates:
- Query=foo, ba.
如果請求參數(shù)里包含foo
參數(shù),并且值匹配為ba.
表達式统倒,則將會被路由寨典,如:bar
and baz
4.10 RemoteAddr 路由斷言 Factory
RemoteAddr 路由斷言 Factory的參數(shù)為 一個CIDR符號(IPv4或IPv6)字符串的列表,最小值為1房匆,例如192.168.0.1/16(其中192.168.0.1是IP地址并且16是子網(wǎng)掩碼)耸成。
application.yml.
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: http://example.org
predicates:
- RemoteAddr=192.168.1.1/24
如果請求的remote address 為 192.168.1.10
則將被路由
4.10.1 修改遠程地址的解析方式
默認(rèn)情況下,RemoteAddr 路由斷言 Factory使用傳入請求中的remote address浴鸿。如果Spring Cloud Gateway位于代理層后面井氢,則可能與實際客戶端IP地址不匹配。
可以通過設(shè)置自定義RemoteAddressResolver
來自定義解析遠程地址的方式岳链。Spring Cloud Gateway網(wǎng)關(guān)附帶一個非默認(rèn)遠程地址解析程序花竞,它基于X-Forwarded-For header, XForwardedRemoteAddressResolver
.
XForwardedRemoteAddressResolver
有兩個靜態(tài)構(gòu)造函數(shù)方法,采用不同的安全方法:
XForwardedRemoteAddressResolver::TrustAll
返回一個RemoteAddressResolver
掸哑,它始終采用X-Forwarded-for
頭中找到的第一個IP地址约急。這種方法容易受到欺騙,因為惡意客戶端可能會為解析程序接受的“x-forwarded-for”設(shè)置初始值举户。XForwardedRemoteAddressResolver::MaxTrustedIndex
獲取一個索引烤宙,該索引與在Spring Cloud網(wǎng)關(guān)前運行的受信任基礎(chǔ)設(shè)施數(shù)量相關(guān)。例如俭嘁,如果SpringCloudGateway只能通過haproxy訪問酬凳,則應(yīng)使用值1轧粟。如果在訪問Spring Cloud Gateway之前需要兩個受信任的基礎(chǔ)架構(gòu)躍點,那么應(yīng)該使用2婿着。
給定以下的header值:
X-Forwarded-For: 0.0.0.1, 0.0.0.2, 0.0.0.3
下面的` maxTrustedIndex值將生成以下遠程地址:
Java 配置方式:
GatewayConfig.java
RemoteAddressResolver resolver = XForwardedRemoteAddressResolver
.maxTrustedIndex(1);
...
.route("direct-route",
r -> r.remoteAddr("10.1.1.1", "10.10.1.1/24")
.uri("https://downstream1")
.route("proxied-route",
r -> r.remoteAddr(resolver, "10.10.1.1", "10.10.1.1/24")
.uri("https://downstream2")
)
5. GatewayFilter Factories
過濾器允許以某種方式修改傳入的HTTP請求或返回的HTTP響應(yīng)罢猪。過濾器的作用域是某些特定路由近她。Spring Cloud Gateway包括許多內(nèi)置的 Filter工廠。
注意:有關(guān)如何使用以下任何過濾器的更詳細示例膳帕,請查看unit tests.粘捎。
5.1 AddRequestHeader GatewayFilter Factory
采用一對名稱和值作為參數(shù)
application.yml.
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: http://example.org
filters:
- AddRequestHeader=X-Request-Foo, Bar
對于所有匹配的請求,這將向下游請求的頭中添加 x-request-foo:bar
header
5.2 AddRequestParameter GatewayFilter Factory
采用一對名稱和值作為參數(shù)
application.yml.
spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: http://example.org
filters:
- AddRequestParameter=foo, bar
對于所有匹配的請求危彩,這將向下游請求添加foo=bar
查詢字符串
5.3 AddResponseHeader GatewayFilter Factory
采用一對名稱和值作為參數(shù)
application.yml.
spring:
cloud:
gateway:
routes:
- id: add_request_header_route
uri: http://example.org
filters:
- AddResponseHeader=X-Response-Foo, Bar
對于所有匹配的請求攒磨,這會將x-response-foo:bar
頭添加到下游響應(yīng)的header中
5.4 Hystrix GatewayFilter Factory
Hystrix 是Netflix開源的斷路器組件。Hystrix GatewayFilter允許你向網(wǎng)關(guān)路由引入斷路器汤徽,保護你的服務(wù)不受級聯(lián)故障的影響娩缰,并允許你在下游故障時提供fallback響應(yīng)。
要在項目中啟用Hystrix網(wǎng)關(guān)過濾器谒府,需要添加對 spring-cloud-starter-netflix-hystrix
的依賴 Spring Cloud Netflix.
Hystrix GatewayFilter Factory 需要一個name參數(shù)拼坎,即HystrixCommand
的名稱浮毯。
application.yml.
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: http://example.org
filters:
- Hystrix=myCommandName
這將剩余的過濾器包裝在命令名為“myCommandName”的HystrixCommand
中。
hystrix過濾器還可以接受可選的fallbackUri
參數(shù)泰鸡。目前债蓝,僅支持forward:
預(yù)設(shè)的URI,如果調(diào)用fallback盛龄,則請求將轉(zhuǎn)發(fā)到與URI匹配的控制器惦蚊。
application.yml.
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: lb://backing-service:8088
predicates:
- Path=/consumingserviceendpoint
filters:
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/incaseoffailureusethis
- RewritePath=/consumingserviceendpoint, /backingserviceendpoint
當(dāng)調(diào)用hystrix fallback時,這將轉(zhuǎn)發(fā)到/incaseoffailureusethis
uri讯嫂。注意蹦锋,這個示例還演示了(可選)通過目標(biāo)URI上的'lb`前綴,使用Spring Cloud Netflix Ribbon 客戶端負(fù)載均衡。
主要場景是使用fallbackUri
到網(wǎng)關(guān)應(yīng)用程序中的內(nèi)部控制器或處理程序欧芽。但是莉掂,也可以將請求重新路由到外部應(yīng)用程序中的控制器或處理程序,如:
application.yml.
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
在本例中千扔,gateway應(yīng)用程序中沒有 fallback
實現(xiàn)憎妙,但是另一個應(yīng)用程序中有一個接口實現(xiàn),注冊為“http://localhost:9994”曲楚。
在將請求轉(zhuǎn)發(fā)到fallback的情況下厘唾,Hystrix Gateway過濾還支持直接拋出Throwable
。它被作為ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR
屬性添加到ServerWebExchange
中龙誊,可以在處理網(wǎng)關(guān)應(yīng)用程序中的fallback時使用抚垃。
對于外部控制器/處理程序方案,可以添加帶有異常詳細信息的header趟大『资鳎可以在 FallbackHeaders GatewayFilter Factory section.中找到有關(guān)它的更多信息。
hystrix配置參數(shù)(如 timeouts)可以使用全局默認(rèn)值配置逊朽,也可以使用Hystrix wiki中所述屬性進行配置罕伯。
要為上面的示例路由設(shè)置5秒超時,將使用以下配置:
application.yml.
hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000
5.5 FallbackHeaders GatewayFilter Factory
FallbackHeaders
允許在轉(zhuǎn)發(fā)到外部應(yīng)用程序中的FallbackUri
的請求的header中添加Hystrix異常詳細信息叽讳,如下所示:
application.yml.
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
在本例中追他,在運行HystrixCommand
發(fā)生執(zhí)行異常后,請求將被轉(zhuǎn)發(fā)到 localhost:9994
應(yīng)用程序中的 fallback
終端或程序岛蚤。異常類型邑狸、消息(如果可用)cause exception類型和消息的頭,將由FallbackHeaders
filter添加到該請求中灭美。
通過設(shè)置下面列出的參數(shù)值及其默認(rèn)值推溃,可以在配置中覆蓋headers的名稱:
-
executionExceptionTypeHeaderName
("Execution-Exception-Type"
) -
executionExceptionMessageHeaderName
("Execution-Exception-Message"
) -
rootCauseExceptionTypeHeaderName
("Root-Cause-Exception-Type"
) -
rootCauseExceptionMessageHeaderName
("Root-Cause-Exception-Message"
)
Hystrix 如何實現(xiàn)的更多細節(jié)可以參考 Hystrix GatewayFilter Factory section.
5.6 PrefixPath GatewayFilter Factory
PrefixPath GatewayFilter 只有一個 prefix
參數(shù).
application.yml.
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: http://example.org
filters:
- PrefixPath=/mypath
這將給所有匹配請求的路徑加前綴/mypath
。因此,向/hello
發(fā)送的請求將發(fā)送到/mypath/hello
铁坎。
5.7 PreserveHostHeader GatewayFilter Factory
該filter沒有參數(shù)蜂奸。設(shè)置了該Filter后,GatewayFilter將不使用由HTTP客戶端確定的host header 硬萍,而是發(fā)送原始host header 扩所。
application.yml.
spring:
cloud:
gateway:
routes:
- id: preserve_host_route
uri: http://example.org
filters:
- PreserveHostHeader
5.8 RequestRateLimiter GatewayFilter Factory
RequestRateLimiter使用RateLimiter
實現(xiàn)是否允許繼續(xù)執(zhí)行當(dāng)前請求。如果不允許繼續(xù)執(zhí)行朴乖,則返回HTTP 429 - Too Many Requests
(默認(rèn)情況下)祖屏。
這個過濾器可以配置一個可選的keyResolver
參數(shù)和rate limiter參數(shù)(見下文)。
keyResolver
是 KeyResolver
接口的實現(xiàn)類.在配置中买羞,按名稱使用SpEL引用bean袁勺。#{@myKeyResolver}
是引用名為'myKeyResolver'的bean的SpEL表達式。
KeyResolver.java.
public interface KeyResolver {
Mono<String> resolve(ServerWebExchange exchange);
}
KeyResolver
接口允許使用可插拔策略來派生限制請求的key畜普。在未來的里程碑版本中期丰,將有一些KeyResolver
實現(xiàn)。
KeyResolver
的默認(rèn)實現(xiàn)是PrincipalNameKeyResolver
吃挑,它從ServerWebExchange
檢索Principal
并調(diào)用Principal.getName()
钝荡。
默認(rèn)情況下,如果KeyResolver
沒有獲取到key舶衬,請求將被拒絕埠通。此行為可以使用 spring.cloud.gateway.filter.request-rate-limiter.deny-empty-key
(true or false) 和 spring.cloud.gateway.filter.request-rate-limiter.empty-key-status-code
屬性進行調(diào)整。
說明
無法通過"shortcut" 配置RequestRateLimiter逛犹。以下示例無效
application.properties.
# INVALID SHORTCUT CONFIGURATION
spring.cloud.gateway.routes[0].filters[0]=RequestRateLimiter=2, 2, #{@userkeyresolver}
5.8.1 Redis RateLimiter
Redis的實現(xiàn)基于 Stripe實現(xiàn)端辱。它需要使用 spring-boot-starter-data-redis-reactive
Spring Boot starter。
使用的算法是Token Bucket Algorithm.圾浅。
redis-rate-limiter.replenishRate
是你允許用戶每秒執(zhí)行多少請求掠手,而丟棄任何請求。這是令牌桶的填充速率狸捕。
``redis-rate-limiter.burstCapacity`是允許用戶在一秒鐘內(nèi)執(zhí)行的最大請求數(shù)。這是令牌桶可以保存的令牌數(shù)众雷。將此值設(shè)置為零將阻止所有請求灸拍。
穩(wěn)定速率是通過在replenishRate
和 burstCapacity
中設(shè)置相同的值來實現(xiàn)的±。可通過設(shè)置burstCapacity
高于replenishRate
來允許臨時突發(fā)流浪鸡岗。在這種情況下,限流器需要在兩次突發(fā)之間留出一段時間(根據(jù)replenishRate
)编兄,因為連續(xù)兩次突發(fā)將導(dǎo)致請求丟失 (HTTP 429 - Too Many Requests
).轩性。
application.yml.
spring:
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: http://example.org
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
Config.java.
@Bean
KeyResolver userKeyResolver() {
return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}
這定義了每個用戶10個請求的限制。允許20個突發(fā)狠鸳,但下一秒只有10個請求可用揣苏。KeyResolver
是一個簡單的獲取user
請求參數(shù)的工具(注意:不建議用于生產(chǎn))悯嗓。
限流器也可以定義為RateLimiter
接口的實現(xiàn) bean。在配置中卸察,按名稱使用SpEL引用bean脯厨。#{@myRateLimiter}
是引用名為'myRateLimiter'的bean的SpEL表達式。
application.yml.
spring:
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: http://example.org
filters:
- name: RequestRateLimiter
args:
rate-limiter: "#{@myRateLimiter}"
key-resolver: "#{@userKeyResolver}"
5.9 RedirectTo GatewayFilter Factory
該過濾器有一個 status
和一個 url
參數(shù)坑质。status是300類重定向HTTP代碼合武,如301。該URL應(yīng)為有效的URL涡扼,這將是 Location
header的值稼跳。
application.yml.
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: http://example.org
filters:
- RedirectTo=302, http://acme.org
這將發(fā)送一個302狀態(tài)碼和一個Location:http://acme.org
header來執(zhí)行重定向。
5.10 RemoveNonProxyHeaders GatewayFilter Factory
RemoveNonProxyHeaders GatewayFilter Factory 從轉(zhuǎn)發(fā)請求中刪除headers吃沪。刪除的默認(rèn)頭列表來自 IETF.
The default removed headers are:
- Connection
- Keep-Alive
- Proxy-Authenticate
- Proxy-Authorization
- TE
- Trailer
- Transfer-Encoding
- Upgrade
要更改此設(shè)置汤善,請將spring.cloud.gateway.filter.remove-non-proxy-headers.headers
屬性設(shè)置為要刪除的header名稱。
5.11 RemoveRequestHeader GatewayFilter Factory
有一個name
參數(shù). 這是要刪除的header的名稱巷波。
application.yml.
spring:
cloud:
gateway:
routes:
- id: removerequestheader_route
uri: http://example.org
filters:
- RemoveRequestHeader=X-Request-Foo
這將在X-Request-Foo
header被發(fā)送到下游之前刪除它萎津。
5.12 RemoveResponseHeader GatewayFilter Factory
有一個name
參數(shù). 這是要刪除的header的名稱。
application.yml.
spring:
cloud:
gateway:
routes:
- id: removeresponseheader_route
uri: http://example.org
filters:
- RemoveResponseHeader=X-Response-Foo
這將在返回到網(wǎng)關(guān)client之前從響應(yīng)中刪除x-response-foo
頭抹镊。
5.13 RewritePath GatewayFilter Factory
包含一個 regexp
正則表達式參數(shù)和一個 replacement
參數(shù). 通過使用Java正則表達式靈活地重寫請求路徑锉屈。
application.yml.
spring:
cloud:
gateway:
routes:
- id: rewritepath_route
uri: http://example.org
predicates:
- Path=/foo/**
filters:
- RewritePath=/foo/(?<segment>.*), /$\{segment}
對于請求路徑/foo/bar
,將在發(fā)出下游請求之前將路徑設(shè)置為/bar
垮耳。注意,由于YAML規(guī)范颈渊,請使用 $\
替換 $
。
5.14 RewriteResponseHeader GatewayFilter Factory
包含 name
, regexp
和 replacement
參數(shù).终佛。通過使用Java正則表達式靈活地重寫響應(yīng)頭的值俊嗽。
application.yml.
spring:
cloud:
gateway:
routes:
- id: rewriteresponseheader_route
uri: http://example.org
filters:
- RewriteResponseHeader=X-Response-Foo, , password=[^&]+, password=***
對于一個/42?user=ford&password=omg!what&flag=true
的header值,在做下游請求時將被設(shè)置為/42?user=ford&password=***&flag=true
铃彰,由于YAML規(guī)范绍豁,請使用 $\
替換 $
。
5.15 SaveSession GatewayFilter Factory
SaveSession GatewayFilter Factory將調(diào)用轉(zhuǎn)發(fā)到下游之前強制執(zhí)行WebSession::save
操作牙捉。這在使用 Spring Session 之類時特別有用竹揍,需要確保會話狀態(tài)在進行轉(zhuǎn)發(fā)調(diào)用之前已保存。
application.yml.
spring:
cloud:
gateway:
routes:
- id: save_session
uri: http://example.org
predicates:
- Path=/foo/**
filters:
- SaveSession
如果你希望要將[Spring Security](https://projects.spring.io/Spring Security/)與Spring Session集成,并確保安全詳細信息已轉(zhuǎn)發(fā)到遠程的進程邪铲,這一點至關(guān)重要芬位。
5.16 SecureHeaders GatewayFilter Factory
SecureHeaders GatewayFilter Factory 將許多headers添加到reccomedation處的響應(yīng)中,從this blog post.
添加以下標(biāo)題(使用默認(rèn)值分配):
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
要更改默認(rèn)值带到,請在spring.cloud.gateway.filter.secure-headers
命名空間中設(shè)置相應(yīng)的屬性:
Property to change:
xss-protection-header
strict-transport-security
frame-options
content-type-options
referrer-policy
content-security-policy
download-options
permitted-cross-domain-policies
5.17 SetPath GatewayFilter Factory
SetPath GatewayFilter Factory 采用 template
路徑參數(shù)昧碉。它提供了一種通過允許路徑的模板化segments來操作請求路徑的簡單方法。使用Spring Framework中的URI模板,允許多個匹配segments被饿。
application.yml.
spring:
cloud:
gateway:
routes:
- id: setpath_route
uri: http://example.org
predicates:
- Path=/foo/{segment}
filters:
- SetPath=/{segment}
對于一個 /foo/bar
請求四康,在做下游請求前,路徑將被設(shè)置為/bar
5.18 SetResponseHeader GatewayFilter Factory
SetResponseHeader GatewayFilter Factory 包括 name
和 value
參數(shù).
application.yml.
spring:
cloud:
gateway:
routes:
- id: setresponseheader_route
uri: http://example.org
filters:
- SetResponseHeader=X-Response-Foo, Bar
此GatewayFilter使用給定的名稱替換所有header锹漱,而不是添加箭养。因此,如果下游服務(wù)器響應(yīng)為X-Response-Foo:1234
哥牍,則會將其替換為X-Response-Foo:Bar
,這是網(wǎng)關(guān)客戶端將接收的內(nèi)容毕泌。
5.19 SetStatus GatewayFilter Factory
SetStatus GatewayFilter Factory 包括唯一的 status
參數(shù).必須是一個可用的Spring HttpStatus
。它可以是整數(shù)值404
或字符串枚舉NOT_FOUND
嗅辣。
application.yml.
spring:
cloud:
gateway:
routes:
- id: setstatusstring_route
uri: http://example.org
filters:
- SetStatus=BAD_REQUEST
- id: setstatusint_route
uri: http://example.org
filters:
- SetStatus=401
在這個例子中撼泛,HTTP返回碼將設(shè)置為401.
5.20 StripPrefix GatewayFilter Factory
StripPrefix GatewayFilter Factory 包括一個parts
參數(shù)。 parts
參數(shù)指示在將請求發(fā)送到下游之前澡谭,要從請求中去除的路徑中的節(jié)數(shù)愿题。
application.yml.
spring:
cloud:
gateway:
routes:
- id: nameRoot
uri: http://nameservice
predicates:
- Path=/name/**
filters:
- StripPrefix=2
當(dāng)通過網(wǎng)關(guān)發(fā)出/name/bar/foo
請求時,向nameservice
發(fā)出的請求將是http://nameservice/foo
蛙奖。
5.21 Retry GatewayFilter Factory
Retry GatewayFilter Factory包括 retries
, statuses
, methods
和 series
參數(shù).
-
retries
: 應(yīng)嘗試的重試次數(shù) -
statuses
: 應(yīng)該重試的HTTP狀態(tài)代碼潘酗,用org.springframework.http.HttpStatus
標(biāo)識 -
methods
: 應(yīng)該重試的HTTP方法,用org.springframework.http.HttpMethod
標(biāo)識 -
series
: 要重試的一系列狀態(tài)碼雁仲,用org.springframework.http.HttpStatus.Series
標(biāo)識
application.yml.
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
注意
retry filter 不支持body請求的重試仔夺,如通過body的POST 或 PUT請求
注意
在使用帶有前綴為forward:
的retry filter
時,應(yīng)仔細編寫目標(biāo)端點攒砖,以便在出現(xiàn)錯誤時不會執(zhí)行任何可能導(dǎo)致將響應(yīng)發(fā)送到客戶端并提交的操作缸兔。例如,如果目標(biāo)端點是帶注解的controller吹艇,則目標(biāo)controller方法不應(yīng)返回帶有錯誤狀態(tài)代碼的ResponseEntity
惰蜜。相反,它應(yīng)該拋出一個Exception
受神,或者發(fā)出一個錯誤信號抛猖,例如通過Mono.error(ex)
返回值,重試過濾器可以配置為通過重試來處理鼻听。
5.22 RequestSize GatewayFilter Factory
當(dāng)請求大小大于允許的限制時樟结,RequestSize GatewayFilter Factory可以限制請求不到達下游服務(wù)。過濾器以RequestSize
作為參數(shù)精算,這是定義請求的允許大小限制(以字節(jié)為單位)。
application.yml.
spring:
cloud:
gateway:
routes:
- id: request_size_route
uri: http://localhost:8080/upload
predicates:
- Path=/upload
filters:
- name: RequestSize
args:
maxSize: 5000000
當(dāng)請求因大小而被拒絕時碎连, RequestSize GatewayFilter Factory 將響應(yīng)狀態(tài)設(shè)置為413 Payload Too Large
灰羽,并帶有額外的header errorMessage
。下面是一個 errorMessage
的例子。
errorMessage
: Request size is larger than permissible limit. Request size is 6.0 MB where permissible limit is 5.0 MB
注意
如果未在路由定義中作為filter參數(shù)提供廉嚼,則默認(rèn)請求大小將設(shè)置為5 MB玫镐。
5.23 Modify Request Body GatewayFilter Factory
這個過濾器被定義為beta版本,將來API可能會改變怠噪。
此過濾器可用于在請求主體被網(wǎng)關(guān)發(fā)送到下游之前對其進行修改恐似。
注意
只能使用Java DSL配置此過濾器
@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;
}
}
5.24 Modify Response Body GatewayFilter Factory
這個過濾器被定義為beta版本,將來API可能會改變傍念。
此過濾器可用于在將響應(yīng)正文發(fā)送回客戶端之前對其進行修改矫夷。
注意
只能使用Java DSL配置此過濾器
@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();
}
6. Global Filters
GlobalFilter
接口與GatewayFilter
具有相同的簽名。是有條件地應(yīng)用于所有路由的特殊過濾器憋槐。(此接口和用法可能在將來的里程碑版本中發(fā)生更改)双藕。
6.1 全局Filter和GatewayFilter組合排序
當(dāng)請求進入(并與路由匹配)時,篩選Web Handler 會將GlobalFilter
的所有實例和所有的GatewayFilter
路由特定實例添加到 filter chain阳仔。filter組合的排序由org.springframework.core.Ordered
接口決定忧陪,可以通過實現(xiàn)getOrde()
方法或使用@Order
注釋來設(shè)置。
由于Spring Cloud Gateway將用于執(zhí)行過濾器邏輯區(qū)分為“前置”和“后置”階段近范,具有最高優(yōu)先級的過濾器將是“前置”階段的第一個嘶摊,而“后置”階段的最后一個。
ExampleConfiguration.java.
@Bean
@Order(-1)
public GlobalFilter a() {
return (exchange, chain) -> {
log.info("first pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("third post filter");
}));
};
}
@Bean
@Order(0)
public GlobalFilter b() {
return (exchange, chain) -> {
log.info("second pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("second post filter");
}));
};
}
@Bean
@Order(1)
public GlobalFilter c() {
return (exchange, chain) -> {
log.info("third pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("first post filter");
}));
};
}
6.2 Forward Routing Filter
ForwardRoutingFilter
在exchange屬性ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR
中查找URI评矩。如果URL有一個forward
scheme (如 forward:///localendpoint
)叶堆,它將使用Spring DispatcherHandler
來處理請求。請求URL的路徑部分將被轉(zhuǎn)發(fā)URL中的路徑覆蓋稚照。未修改的原始URL將附加到 ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR
屬性中的列表中蹂空。
6.3 LoadBalancerClient Filter
LoadBalancerClientFilter
在exchange屬性ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR
中查找URI。如果URL有一個lb
scheme (如 lb://myservice
)果录,它將使用Spring Cloud LoadBalancerClient
將名稱(在前一個示例中為'myservice)解析為實際主機和端口上枕,并替換URI。未修改的原始URL將附加到
ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR屬性中的列表中弱恒。過濾器還將查看
ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR屬性辨萍,查看它是否等于
lb`,然后應(yīng)用相同的規(guī)則返弹。
application.yml.
spring:
cloud:
gateway:
routes:
- id: myRoute
uri: lb://service
predicates:
- Path=/service/**
注意
默認(rèn)情況下锈玉,如果一個服務(wù)實例在LoadBalancer
中沒有發(fā)現(xiàn),則返回503义起±常可以通過設(shè)置spring.cloud.gateway.loadbalancer.use404=true
來讓網(wǎng)管返回404.
注意
從LoadBalancer
返回的ServiceInstance
的isSecure
值將覆蓋在對網(wǎng)關(guān)發(fā)出的請求中指定的scheme。例如默终,如果請求通過HTTPS
進入網(wǎng)關(guān)椅棺,但ServiceInstance
表示它不安全犁罩,則下游請求將通過HTTP
協(xié)議。相反的情況也適用两疚。但是床估,如果在網(wǎng)關(guān)配置中為路由指定了GATEWAY_SCHEME_PREFIX_ATTR
,則前綴將被刪除诱渤,并且路由URL生成的scheme將覆蓋ServiceInstance
配置丐巫。
6.4 Netty Routing Filter
如果位于 ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR
屬性中的URL具有http
或https
模式,則會運行Netty Routing Filter勺美。它使用Netty HttpClient
發(fā)出下游代理請求递胧。響應(yīng)放在 ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR
exchange屬性中,以便在以后的過濾器中使用励烦。(有一個實驗階段不需要Netty的相同的功能的Filter谓着,WebClientHttpRoutingFilter
)
6.5 Netty Write Response Filter
如果ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR
exchange屬性中存在 Netty HttpClientResponse
,則運行 NettyWriteResponseFilter
坛掠。它在其他所有過濾器完成后將代理響應(yīng)寫回網(wǎng)關(guān)客戶端響應(yīng)之后運行赊锚。(有一個不需要netty的實驗性的WebClientWriteResponseFilter
執(zhí)行相同的功能)
6.6 RouteToRequestUrl Filter
如果ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR
exchange屬性中存在Route
對象,RouteToRequestUrlFilter
將運行屉栓。它基于請求URI創(chuàng)建一個新的URI舷蒲,使用Route
對象的uri屬性進行更新。新的URI被放置在ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR
exchange屬性中友多。
如果該URI有一個前綴scheme牲平,例如lb:ws://serviceid
,則會從該URI中剝離該 lb
scheme域滥,并將其放置在ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR
中纵柿,以便稍后在過濾器鏈中使用。
6.7 Websocket Routing Filter
如果ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR
exchange屬性中有 ws
启绰、 wss
scheme昂儒,則Websocket Routing Filter將被運行。它使用Spring Web Socket基礎(chǔ)模塊將Websocket轉(zhuǎn)發(fā)到下游委可。
URI前綴為lb
的Websockets可以被負(fù)載均衡渊跋,如 lb:ws://serviceid
.
注意
如果使用 SockJS 作為普通HTTP的fallback,則應(yīng)配置普通HTTP路由以及WebSocket路由着倾。
application.yml.
spring:
cloud:
gateway:
routes:
# SockJS route
- id: websocket_sockjs_route
uri: http://localhost:3001
predicates:
- Path=/websocket/info/**
# Normwal Websocket route
- id: websocket_route
uri: ws://localhost:3001
predicates:
- Path=/websocket/**
6.8 Gateway Metrics Filter
要啟用網(wǎng)關(guān)指標(biāo)拾酝,請將spring-boot-starter-actuator添加為項目依賴項。然后卡者,默認(rèn)情況下蒿囤,只要屬性spring.cloud.gateway.metrics.enabled
未設(shè)置為false
,網(wǎng)關(guān)指標(biāo)過濾器就會運行崇决。此過濾器添加名為“gateway.requests”的計時器指標(biāo)蟋软,并帶有以下標(biāo)記:
-
routeId
: The route id -
routeUri
: API 將被轉(zhuǎn)發(fā)的URI -
outcome
: 結(jié)果分類依據(jù) HttpStatus.Series -
status
: 返回client的請求的Http Status
這些指標(biāo)可以從/actuator/metrics/gateway.requests
中獲取镶摘,可以很容易地與Prometheus集成以創(chuàng)建Grafana dashboard.
注意
要將pometheus啟用,需要添加 micrometer-registry-prometheus為項目依賴岳守。
6.9 Making An Exchange As Routed
網(wǎng)關(guān)路由ServerWebExchange
之后,它將通過向Exchange屬性添加gatewayAlreadyRouted
碌冶,將該exchange標(biāo)記為“routed”湿痢。一旦一個請求被標(biāo)記為routed,其他路由過濾器將不會再次路由該請求扑庞,將跳過該過濾器譬重。有一些方便的方法可以用來將exchange標(biāo)記為routed,或者檢查exchange是否已經(jīng)routed罐氨。
-
ServerWebExchangeUtils.isAlreadyRouted
有一個ServerWebExchange
對象并檢查它是否已"routed" -
ServerWebExchangeUtils.setAlreadyRouted
有一個ServerWebExchange
對象并將其標(biāo)記為"routed"
7. TLS / SSL
網(wǎng)關(guān)可以通過常規(guī)的 Spring server configuration 來偵聽HTTPS上的請求臀规。例子:
application.yml.
server:
ssl:
enabled: true
key-alias: scg
key-store-password: scg1234
key-store: classpath:scg-keystore.p12
key-store-type: PKCS12
網(wǎng)關(guān)路由可以路由到HTTP和HTTPS后端。如果路由到HTTPS后端栅隐,則可以將網(wǎng)關(guān)配置為信任所有具有證書的下游服務(wù):
application.yml.
spring:
cloud:
gateway:
httpclient:
ssl:
useInsecureTrustManager: true
不建議在生產(chǎn)環(huán)境使用不安全的信任管理器塔嬉。對于生產(chǎn)部署,可以使用一組已知證書配置網(wǎng)關(guān)租悄,這些證書可以通過以下方式進行配置:
application.yml.
spring:
cloud:
gateway:
httpclient:
ssl:
trustedX509Certificates:
- cert1.pem
- cert2.pem
如果Spring Cloud Gateway未配置受信任證書谨究,則使用默認(rèn)信任庫(可以使用系統(tǒng)屬性javax.net.ssl.trustStore覆蓋)。
7.1 TLS 握手
網(wǎng)關(guān)維護一個用于路由到后端的client池泣棋。當(dāng)通過HTTPS通信時胶哲,客戶端啟動一個TLS握手,其中可能會有很多超時潭辈。這些超時可以這樣配置(顯示默認(rèn)值):
application.yml.
spring:
cloud:
gateway:
httpclient:
ssl:
handshake-timeout-millis: 10000
close-notify-flush-timeout-millis: 3000
close-notify-read-timeout-millis: 0
8. Configuration
Spring Cloud Gateway的配置由RouteDefinitionLocator
的集合驅(qū)動鸯屿。
RouteDefinitionLocator.java.
public interface RouteDefinitionLocator {
Flux<RouteDefinition> getRouteDefinitions();
}
默認(rèn)情況下,PropertiesRouteDefinitionLocator
使用Spring Boot的@ConfigurationProperties
機制加載屬性把敢。
以下兩個示例是等效的:
application.yml.
spring:
cloud:
gateway:
routes:
- id: setstatus_route
uri: http://example.org
filters:
- name: SetStatus
args:
status: 401
- id: setstatusshortcut_route
uri: http://example.org
filters:
- SetStatus=401
對于網(wǎng)關(guān)的大部分用法寄摆,配置文件方式是夠用的,但一些生產(chǎn)用例更建議從外部源(如數(shù)據(jù)庫)加載配置技竟。未來的里程碑版本將有基于Spring Data Repositories (如Redis冰肴、MongoDB和Cassandra)的RouteDefinitionLocator
實現(xiàn)。
8.1 Fluent Java Routes API
為了可以更簡單在Java中配置榔组,在RouteLocatorBuilder
bean中定義了一個fluent API熙尉。
GatewaySampleApplication.java.
// static imports from GatewayFilters and RoutePredicates
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
return builder.routes()
.route(r -> r.host("**.abc.org").and().path("/image/png")
.filters(f ->
f.addResponseHeader("X-TestHeader", "foobar"))
.uri("http://httpbin.org:80")
)
.route(r -> r.path("/image/webp")
.filters(f ->
f.addResponseHeader("X-AnotherHeader", "baz"))
.uri("http://httpbin.org:80")
)
.route(r -> r.order(-1)
.host("**.throttle.org").and().path("/get")
.filters(f -> f.filter(throttle.apply(1,
1,
10,
TimeUnit.SECONDS)))
.uri("http://httpbin.org:80")
)
.build();
}
這種樣式還允許使用更多的自定義斷言。由RouteDefinitionLocator
beans定義的斷言使用邏輯 and
組合搓扯。通過使用fluent Java API检痰,可以在 Predicate
類上使用 and()
、or()
锨推、 negate()
運算符铅歼。
8.2 DiscoveryClient Route Definition Locator
可以將網(wǎng)關(guān)配置為基于使用兼容DiscoveryClient
注冊中心注冊的服務(wù)來創(chuàng)建路由公壤。
要啟用此功能,請設(shè)置spring.cloud.gateway.discovery.locator.enabled=true
椎椰,并確保DiscoveryClient
實現(xiàn)位于classpath上并已啟用(如netflix eureka厦幅、consul或zookeeper)。
8.2.1 Configuring Predicates and Filters For DiscoveryClient Routes
默認(rèn)情況下慨飘,網(wǎng)關(guān)為通過DiscoveryClient
創(chuàng)建的路由定義單個斷言和過濾器确憨。
默認(rèn)斷言是使用/serviceId/**
定義的path斷言,其中serviceId
是DiscoveryClient
中服務(wù)的ID瓤的。
默認(rèn)過濾器是使用正則表達式 /serviceId/(?<remaining>.*)
和替換的/${remaining}
進行重寫休弃。這只是在請求被發(fā)送到下游之前從路徑中截取掉 service id 。
可以通過設(shè)置spring.cloud.gateway.discovery.locator.predicates[x]
and spring.cloud.gateway.discovery.locator.filters[y]
來實現(xiàn)自定義DiscoveryClient
路由使用的斷言and/or過濾器圈膏。當(dāng)你這樣做時塔猾,如果你想要保留這個功能,你需要確保包括上面的默認(rèn)斷言和過濾器稽坤。下面是這樣一個例子丈甸。
application.properties.
spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'"
spring.cloud.gateway.discovery.locator.predicates[1].name: Host
spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'**.foo.com'"
spring.cloud.gateway.discovery.locator.filters[0].name: Hystrix
spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId
spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath
spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/(?<remaining>.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"
9. Reactor Netty Access Logs
設(shè)置 -Dreactor.netty.http.server.accessLogEnabled=true
來開啟Reactor Netty access logs,注意必須是Java System Property而不是Spring Boot property慎皱。
logging 模塊也可以通過配置單獨輸出一個access log文件老虫,下面是logback的配置例子:
logback.xml.
<appender name="accessLog" class="ch.qos.logback.core.FileAppender">
<file>access_log.log</file>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>
<appender name="async" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="accessLog" />
</appender>
<logger name="reactor.netty.http.server.AccessLog" level="INFO" additivity="false">
<appender-ref ref="async"/>
</logger>
10. CORS Configuration
我們可以通過配置網(wǎng)關(guān)來控制CORS行為,全局CORS配置是 Spring Framework CorsConfiguration
模式的URL MAP茫多。
application.yml.
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
'[/**]':
allowedOrigins: "http://docs.spring.io"
allowedMethods:
- GET
例子中將允許從docs.spring.io發(fā)出的所有GET請求進行CORS請求祈匙。
11. Actuator API
/gateway
的actuator端點允許監(jiān)視Spring Cloud Gateway應(yīng)用程序并與之交互。要進行遠程訪問天揖,必須在應(yīng)用程序?qū)傩灾斜┞禜TTP或JMX 端口夺欲。
application.properties.
management.endpoint.gateway.enabled=true # default value
management.endpoints.web.exposure.include=gateway
11.1 Retrieving route filters
11.1.1 Global Filters
要檢索應(yīng)用于所有路由的 [global filters],請get請求 /actuator/gateway/globalfilters
今膊。返回的結(jié)果類似于以下內(nèi)容:
{
"org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5": 10100,
"org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@4f6fd101": 10000,
"org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@32d22650": -1,
"org.springframework.cloud.gateway.filter.ForwardRoutingFilter@106459d9": 2147483647,
"org.springframework.cloud.gateway.filter.NettyRoutingFilter@1fbd5e0": 2147483647,
"org.springframework.cloud.gateway.filter.ForwardPathFilter@33a71d23": 0,
"org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@135064ea": 2147483637,
"org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@23c05889": 2147483646
}
返回結(jié)果包含已就緒的global filters的詳細信息(如 org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5
)些阅。對于每個global filters,返回結(jié)果字符串對應(yīng)過濾器鏈中的相應(yīng)順序斑唬。
11.1.2 Route Filters
要檢索應(yīng)用于路由的 [GatewayFilter factories] 市埋,請get請求/actuator/gateway/routefilters
。返回結(jié)果類似于以下內(nèi)容:
{
"[AddRequestHeaderGatewayFilterFactory@570ed9c configClass = AbstractNameValueGatewayFilterFactory.NameValueConfig]": null,
"[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]": null,
"[SaveSessionGatewayFilterFactory@4449b273 configClass = Object]": null
}
返回結(jié)果包含應(yīng)用于所有路由的GatewayFilter的詳細信息恕刘。顯示每個工廠提供字符串格式的相應(yīng)對象(例如缤谎, [SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]
)。請注意褐着,null
值是由于endpoint controller實現(xiàn)不完整造成的坷澡,因為它嘗試在filter chain中設(shè)置對象的順序,這不適用于GatewayFilter工廠對象含蓉。
11.2 Refreshing the route cache
如果要清理路由的緩存频敛,請POST請求/actuator/gateway/refresh
项郊。該請求將返回一個沒有body的200返回碼。
11.3 Retrieving the routes defined in the gateway
要檢索網(wǎng)關(guān)中定義的路由斟赚,發(fā)送GET請求/actuator/gateway/routes
着降,返回結(jié)果如下所示:
[{
"route_id": "first_route",
"route_object": {
"predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@1e9d7e7d",
"filters": [
"OrderedGatewayFilter{delegate=org.springframework.cloud.gateway.filter.factory.PreserveHostHeaderGatewayFilterFactory$$Lambda$436/674480275@6631ef72, order=0}"
]
},
"order": 0
},
{
"route_id": "second_route",
"route_object": {
"predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@cd8d298",
"filters": []
},
"order": 0
}]
返回結(jié)果中包含網(wǎng)關(guān)中所有定義的路由信息,下面表格中描述了返回結(jié)果信息:
11.4 Retrieving information about a particular route
要獲取單個路由的信息汁展,發(fā)送GET請求 /actuator/gateway/routes/{id}
(如: /actuator/gateway/routes/first_route
)鹊碍,返回結(jié)果如下所示:
{
"id": "first_route",
"predicates": [{
"name": "Path",
"args": {"_genkey_0":"/first"}
}],
"filters": [],
"uri": "http://www.uri-destination.org",
"order": 0
}]
下面表格中描述了返回結(jié)果信息:
11.5 Creating and deleting a particular route
要創(chuàng)建一個路由,發(fā)送POST請求 /gateway/routes/{id_route_to_create}
食绿,參數(shù)為JSON結(jié)構(gòu),具體參數(shù)數(shù)據(jù)結(jié)構(gòu)參考上面章節(jié)公罕。
要刪除一個路由器紧,發(fā)送 DELETE
請求 /gateway/routes/{id_route_to_delete}
。
11.6 Recap: list of all endpoints
下表總結(jié)了Spring Cloud Gateway actuator endpoints楼眷。注意铲汪,每個endpoint都是/actuator/gateway
作為基本路徑。
12. Developer Guide
TODO: overview of writing custom integrations
12.1 Writing Custom Route Predicate Factories
TODO: document writing Custom Route Predicate Factories
12.2 Writing Custom GatewayFilter Factories
如果要自定義一個GatewayFilter罐柳,需要實現(xiàn)GatewayFilterFactory
掌腰。下面是一個你需要集成的抽象類 AbstractGatewayFilterFactory
。
PreGatewayFilterFactory.java.
public class PreGatewayFilterFactory extends AbstractGatewayFilterFactory<PreGatewayFilterFactory.Config> {
public PreGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
// grab configuration from Config object
return (exchange, chain) -> {
//If you want to build a "pre" filter you need to manipulate the
//request before calling chain.filter
ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
//use builder to manipulate the request
return chain.filter(exchange.mutate().request(request).build());
};
}
public static class Config {
//Put the configuration properties for your filter here
}
}
PostGatewayFilterFactory.java.
public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory<PostGatewayFilterFactory.Config> {
public PostGatewayFilterFactory() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
// grab configuration from Config object
return (exchange, chain) -> {
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
//Manipulate the response in some way
}));
};
}
public static class Config {
//Put the configuration properties for your filter here
}
}
12.3 Writing Custom Global Filters
TODO: document writing Custom Global Filters
12.4 Writing Custom Route Locators and Writers
TODO: document writing Custom Route Locators and Writers
歡迎關(guān)注 高廣超的簡書博客 與 收藏文章 张吉!
歡迎關(guān)注 頭條號:互聯(lián)網(wǎng)技術(shù)棧 齿梁!
個人介紹:
高廣超:多年一線互聯(lián)網(wǎng)研發(fā)與架構(gòu)設(shè)計經(jīng)驗,擅長設(shè)計與落地高可用肮蛹、高性能勺择、可擴展的互聯(lián)網(wǎng)架構(gòu)。目前從事大數(shù)據(jù)相關(guān)研發(fā)與架構(gòu)工作伦忠。
本文首發(fā)在 高廣超的簡書博客 轉(zhuǎn)載請注明省核!