前言:在上一節中我們實現了SpringCloud Gateway的動態路由?,而在本節中我們將著重介紹各種Route?Predicate的作用。
1、可以到官方文檔里查看常用的Route Predicate的種類
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#the-after-route-predicate-factory
2、After Route Predicate
可以用于提前上線新功能,然后在指定時間后才能路由
spring:cloud:gateway:routes:- id: after_routeuri: https://example.orgpredicates:#這里配置的意思為時間在2017-01-20 17:42:47之后才能路由- After=2017-01-20T17:42:47.789-07:00[America/Denver]
例如,我這里設置2024-05-11 23:15:10之后才能路由
效果圖:?
3、Before route predicate
spring:cloud:gateway:routes:- id: before_routeuri: https://example.orgpredicates:#這里配置的意思時間為在2017-01-20 17:42:47之前才能路由- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
4、Between route predicate
spring:cloud:gateway:routes:- id: between_routeuri: https://example.orgpredicates:#這里配置的意思為時間在2017-01-20 17:42:47到2017-01-21 17:42:47之間才能路由- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]
5、?Cookie route predicate
Cookie Route Predicate需要兩個參數,一個是 Cookie name ,一個是正則表達式;路由規則會通過獲取對應的Cookie name值和正則表達式去匹配,如果匹配上就會執行路由,如果沒有匹配上則不執行
spring:cloud:gateway:routes:- id: cookie_routeuri: https://example.orgpredicates:#這里配置的意思為請求帶上指定的Cookie才能路由- Cookie=chocolate, ch.p
例如,我這里設置指定Cookie是username為ken時才能路由(可以用win+R喚出運行,然后輸入cmd進入命令行模式,然后用curl命令來模擬請求來進行測試)
效果圖:
沒帶Cookie時請求不通過
指定Cookie時請求通過
6、Header route predicate
spring:cloud:gateway:routes:- id: header_routeuri: https://example.orgpredicates:#這里配置的意思為請求頭要有X-Requegt-Id屬性并且值為整數的正則表達式才能路由- Header=X-Request-Id, \d+
例如,我這里設置指定Header=X-Request-Id是整數時才能路由(可以用win+R喚出運行,然后輸入cmd進入命令行模式,然后用curl命令來模擬請求來進行測試)
效果圖:
請求頭X-Requegt-Id屬性的值為字母時請求不通過
?請求頭X-Requegt-Id屬性的值為整數時請求通過
7、Host route predicate
spring:cloud:gateway:routes:- id: host_routeuri: https://example.orgpredicates:#這里配置的意思為請求頭要有Host屬性并且值為**.somehost.org或**.anotherhost.org的正則表達式才能路由- Host=**.somehost.org,**.anotherhost.org
例如,我這里設置指定Host是為**.ken.com時才能路由(可以用win+R喚出運行,然后輸入cmd進入命令行模式,然后用curl命令來模擬請求來進行測試)
效果圖:
請求頭Host屬性的值為www.baid.com時請求不通過
?請求頭Host屬性的值為xxx.ken.com時請求通過
8、Method Route Predicate
spring:cloud:gateway:routes:- id: method_routeuri: https://example.orgpredicates:#這里配置的意思為請求要是GET或者POST才能路由- Method=GET,POST
9、Path Route Predicate
spring:cloud:gateway:routes:- id: host_routeuri: https://example.orgpredicates:#這里配置的意思為請求的路徑要是/red/1 或者 /red/blue 或者 /blue/green才能路由- Path=/red/{segment},/blue/{segment}
例:
效果圖:
10、Query route predicate
spring:cloud:gateway:routes:- id: query_routeuri: https://example.orgpredicates:#這里配置的意思為請求要有參數green才能路由- Query=green
例:
效果圖:
請求帶username,請求通過
請求不帶username,請求不通過