前一章【SpringCloud】Gateway網關入門(十六)介紹的Gateway的基本使用,本章介紹Gateway路由配置
本章使用項目,還是上一章的項目
Gateway的路由配置有2中方式,一種是通過YML配置文件來配置,一種是通過配置類來配置
YML配置文件配置路由
1、指定路徑轉發路由
即根據指定的路徑,進行轉發,案例參考上一章
配置如下:
1 spring: 2 application: 3 name: cloud-gateway-gateway 4 cloud: 5 gateway: 6 routes: 7 # 路由的ID,沒有固定規則,但要求唯一,建議配合服務名 8 - id: payment_routh 9 # 匹配后提供服務的路由地址 10 uri: http://localhost:8001 11 # 斷言,路徑相匹配的進行路由 12 predicates: 13 - Path=/payment/get/**
2、通過服務名實現動態路由
默認情況下Gatway會根據注冊中心注冊的服務列表, 以注冊中心上微服務名為路徑創建動態路由進行轉發,從而實現動態路由的功能
1)在前面項的基礎上,新增一個支付服務模塊,與已有支付模塊相同,參考:【SpringCloud】服務提供者集群與服務發現Discovery(三)
2)修改Gateway網關項目(springcloud-gateway-gateway9527)配置文件application.yml,修改內容如下:
1 spring: 2 application: 3 name: cloud-gateway-gateway 4 cloud: 5 gateway: 6 discovery: 7 locator: 8 # 開啟從注冊中心動態創建路由的功能,利用微服務名進行路由 9 enabled: true 10 # 忽略大小寫匹配,默認為 false。 11 # 當 eureka 自動大寫 serviceId 時很有用。 所以 MYSERIVCE,會匹配 /myservice/** 12 lowerCaseServiceId: true
3)測試
a、啟動項目
b、查看Eureka注冊中心,地址:http://localhost:8761/
c、訪問地址:http://localhost:8002/payment/get/1,驗證支付服務正常
d、訪問地址:http://localhost:9527/cloud-payment-service/payment/get/1,cloud-payment-service 是 支付模塊的服務名稱
驗證動態網關已生效,並且是負載輪詢的方式訪問支付模塊的服務
通過配置類來配置路由
本章演示通過配置類配置訪問百度新聞網站(http://news.baidu.com)
1、訪問百度新聞國內新聞模塊,地址:http://news.baidu.com/guonei,確認新聞地址
2、在以上Gateway網關項目(springcloud-gateway-gateway9527)中,新增配置類,內容如下:
1 @Configuration 2 public class GatewayConfig { 3 4 @Bean 5 public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder){ 6 // 路由構造器 7 RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes(); 8 // 設置路徑 9 routes.route("baidu_news_guonei_routh", r -> { 10 return r.path("/guonei").uri("http://news.baidu.com/guonei"); 11 }); 12 routes.route("baidu_news_guoji_routh", r -> { 13 return r.path("/guoji").uri("http://news.baidu.com/guoji"); 14 }); 15 16 return routes.build(); 17 } 18 }
3、測試
1)啟動項目
2)訪問地址:http://localhost:9527/guonei,驗證通過網關是否能訪問國內新聞
3)訪問地址:http://localhost:9527/guoji,驗證通過網關是否能訪問國際新聞