需求
通過gateway的route規則,實現分組流量配置
資源
一個nacos,一個gateway ,一個服務app(部署雙實例group-1,group-2),實現特定條件下往分組一和分組二流量切換。
方案
1 配置文件
- nacos 默認配置即可
- gateway 配置
server:port: 8062spring:application:name: api-gatewaycloud:gateway:routes:- id: id-group-grepuri: lb://app-group-2predicates:- Header=X-VERSION, v2 # 匹配Header中X-VERSION為v2的請求# - Query=type, mobile2 # 匹配包含type=mobile參數的請求# - Host=192.168.0.73 #這里配置域名 IP貌似不管用# - RemoteAddr=192.168.0.73,192.168.2.0/24,127.0.0.1 # 不建議配置IP 有匹配范圍的風險以及IP變化風險# - Cookie=userType, premium # 匹配包含特定Cookie的請求 沒試- Path=/app/**# - Weight=app-group,1filters:- StripPrefix=1 - id: app-group-produri: lb://app-group-1predicates:- Header=X-VERSION, v1 # 匹配Header中X-VERSION為v2的請求# - Query=type, mobile1 # 匹配包含type=mobile參數的請求# - Host=192.168.0.73 #這里配置域名 IP貌似不管用# - RemoteAddr=192.168.0.73,192.168.2.0/24,127.0.0.1 # 不建議配置IP 有匹配范圍的風險以及IP變化風險# - Cookie=userType, premium # 匹配包含特定Cookie的請求- Path=/app/**# - Weight=app-group,1filters:- StripPrefix=1
- app-group-2:127.0.0.1:8082
寫一個測試Controller 打印? ?hello world22222
@RequestMapping(value = "", method = RequestMethod.GET)public ResultServer<String> hello() {System.out.println("我是group-22222");return new ResultServer().success("hello world22222");}
server:port: 8082 spring:application:name: app-group-2
- app-group-1:127.0.0.1:8081 寫一個測試Controller 打印? ?hello world11111
@RequestMapping(value = "", method = RequestMethod.GET)public ResultServer<String> hello() {System.out.println("我是group-22222");return new ResultServer().success("hello world11111");}
server:port: 8081 spring:application:name: app-group-1
2 啟動四個服務,
- nacos 127.0.0.1:8848
- gateway 127.0.0.1:8209
- app-group-2:127.0.0.1:8082?
- app-group-1:127.0.0.1:8081?
Nacos的注冊情況
驗證Header
- 證明Header是管用的。
驗證Query
證明Query是管用的。
host和別的我就不驗證了,實際生產不太能用的到
除非部署一套灰度的前端環境,這樣可以
1 指定灰度環境的為 grey.*****.com 走灰度分組
2 指定生產環境的為 prod.*****.com 走生產分組
注意
1 網關路由的配置我是放在了nacos上邊,完整的gateway配置文件為;
server:port: 8062spring:application:name: api-gatewaymain:allow-bean-definition-overriding: trueprofiles:active: devcloud:nacos:discovery:server-addr: 127.0.0.1:8848namespace: devconfig:server-addr: 127.0.0.1:8848file-extension: yamlnamespace:devshared-configs[0]:data-id: ${spring.application.name}-route.yamlrefresh: trueusername: @nacos.username@password: @nacos.password@logging:level:com.alibaba.nacos.client.*: WARN
2??predicates 應該是只支持一種類型,要么header 要么query,如果配置兩個,直接就拋異常了。
3 如果設置了斷言,那么權重配比也要去掉,否則會覆蓋斷言配置,依舊走權重的配置
# - Weight=app-group,1。
參考文獻
https://docs.spring.io/spring-cloud-gateway/reference/4.1-SNAPSHOT/spring-cloud-gateway/request-predicates-factories.html