过滤器及断言工厂
斷言工廠
Spring Cloud Gateway包含許多內置的Route Predicate工廠。所有這些斷言都匹配HTTP請求的不同屬性。多路由斷言工廠通過and組合。
官方提供的路由工廠:
這些斷言工廠的配置方式,參照官方文檔:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.0.RELEASE/single/spring-cloud-gateway.html
這里重點掌握請求路徑路由斷言的配置方式:
spring:cloud:gateway:routes:- id: host_routeuri: http://example.orgpredicates:- Path=/foo/{segment},/bar/{segment}這個路由匹配以/foo或者/bar開頭的路徑,轉發到http:example.org。例如 /foo/1 or /foo/bar or /bar/baz.
濾器工廠
路由過濾器允許以某種方式修改傳入的HTTP請求或傳出的HTTP響應。路徑過濾器的范圍限定為特定路由。Spring Cloud Gateway包含許多內置的GatewayFilter工廠。
這些過濾器工廠的配置方式,同樣參照官方文檔:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.1.0.RELEASE/single/spring-cloud-gateway.html
過濾器 有 20 多個 實現類,根據過濾器工廠的用途來劃分,可以分為以下幾種:Header、Parameter、Path、Body、Status、Session、Redirect、Retry、RateLimiter和Hystrix
這里重點掌握PrefixPath GatewayFilter Factory
上面的配置中,所有的/foo/**開始的路徑都會命中配置的router,并執行過濾器的邏輯,在本案例中配置了RewritePath過濾器工廠,此工廠將/foo/(?.*)重寫為{segment},然后轉發到http://example.org。比如在網頁上請求localhost:8090/foo/forezp,此時會將請求轉發到http://example.org/forezp的頁面
?
? 在開發中由于所有微服務的訪問都要經過網關,為了區分不同的微服務,通常會在路徑前加上一個標識,例如:訪問服務提供方:http://localhost:8090/provider/hello ;訪問服務消費方:http://localhost:8090/consumer/hi 如果不重寫地址,直接轉發的話,轉發后的路徑為:http://localhost:8070/provider/hello和http://localhost:8080/consumer/hi明顯多了一個provider或者consumer,導致轉發失敗。
這時,我們就用上了路徑重寫,配置如下:
server:port: 8090 spring:cloud:gateway:routes:- id: nacos-consumeruri: http://127.0.0.1:8080predicates:- Path=/consumer/**filters:- RewritePath=/consumer/(?<segment>.*),/$\{segment}- id: nacos-provideruri: http://127.0.0.1:8070predicates:- Path=/provider/**filters:- RewritePath=/provider/(?<segment>.*),/$\{segment}注意:Path=/consumer/**及Path=/provider/**的變化
測試:
?
總結
- 上一篇: gateway网关配置入门
- 下一篇: 回顾多线程