定制的路由規則的主要功能:
1、路由表中包含源路徑,微服務名稱,目標路徑
2、Endpoint粒度配置支持
3、路由支持1對1精確路由
4、源路徑可以前綴/**格式來模糊路由
5、目標路徑可以使用前綴/**格式來裝配目標路徑
6、保留默認動態路由規則:服務名稱/** --> 是否截去前綴 --> 目標路徑
7、保留默認動態路由規則是否支持截去前綴的配置參數stripPrefix特性
8、路由規則可以在不重啟服務動態更新,這個功能通過外化配置來支持
9、匹配股則采取誰先匹配路由誰,也就是說在路由表中有2個或以上的路由規則可能被匹配到時,匹配最先查詢到的規則
路由規則格式采用properties格式:
源路徑 = 微服務名稱, 目標路徑
啟動時讀取配置並解析,放入路由表。請求時通過查詢匹配到合適的路由轉發。
例如:
/api/v1/trade=trade,/v1/trade /api/customer/**=customer,/api/v1/** /api/user/**=user
在上面的例子中:
- /api/v1/trade會精確的路由到trade微服務的/v1/trade;
- /api/customer/開頭的api會路由轉發到customer微服務的/api/v1/**,其中后面的**會被前面的**部分替換,比如/api/customer/card->/api/v1/card的轉換
- /api/user/開頭的api會路由轉發到user微服務的/api/user/**,endppoint不變
一、直觀顯示路徑到微服務的映射
#localhost:8888/routes(Zuul對應的IP及端口) management: security: enabled: false
二、路由配置
1、靜態路由
#除了“users”服務,其他的服務都會被忽略 zuul: ignoredServices: '*' routes: users: /myusers/** #前端通過/myusers的http訪問,將會被后端“users”服務處理(例如:/myusers/101將會轉發的/101) zuul: routes: users: /myusers/** #將xxx/books后面的所有請求,添加到url后面去 示例:http://localhost:8888/books/xxx->http://localhost:5000/books/avaiable/xxx zuul: routes: books: http://localhost:5000/books/available #books/xxx=>轉化為http://localhost:5000/books/available/xxx 示例:http://localhost:8888/books/xxx==>http://localhost:50000/books/available/xxx server: port: 8888 spring: application: name: zuul-gateway zuul: routes: books: url: http://localhost:5000/books/available #/baidu后的所有直接添加到http://localhost:8080后 示例:http://localhost:8888/baidu/**=>http://localhost:8080/** zuul: routes: baidu: path: /baidu/** url: http://localhost:8080
2、靜態路由+ribbon負載均衡/故障切換
zuul: routes: myroutes1: path: /mypath/** serviceId: myserverId myserverId: ribbon: listOfServers: localhost:8080, localhost:8081 ribbon: eureka: enabled: false
3、動態路由+ribbon負載均衡/故障切換
zuul: routes: myroutes1: path: /mypath/** serviceId: myserviceId eureka: client: serviceUrl: defaultZne:xxx
4、路由匹配配置
stripPrefix=true,轉發會過濾掉前綴 path: /myusers/**,默認時轉發到服務的請求是/**,如果stripPrefix=false,轉發的請求是/myusers/** zuul.prefix=/api 會對所有的path增加一個/api前綴 ignoredPatterns: /**/admin/** 過濾掉匹配的url route: users: /myusers/** 會匹配所有/myusers/**的url,但由於ignoredPatterns, /myusers/**/admin/**的請求不會被轉發,而是直接由zuul里的接口接收
5、匹配順序
path:/myusers/** path:/** 如果是在application.yml中配置的,那么會優先匹配/myusers/** 但如果是applicaiton.properties配置的,那么可能導致/myusers/**被/**覆蓋 ignored-Services: ‘*‘ 對於自動發現的services,除了route中明確指定的,其他都會被忽略
6、請求頭過濾
route.sensitiveHeaders: Cookie,Set-Cookie,Authorization 默認就有這三個請求頭,意思是不向下游轉發請求這幾個頭 zuul.ignoredHeaders 是一個全局設置,而route.sensitiveHeaders是局部設置