之前學習GateWay進行請求的轉發,URI是固定的,也就是在單機的情況下。不過實際開發中,服務很多時候是集群,因此URI就不能寫固定的IP了。而動態路由的方式能夠實現對集群的負載均衡轉發。
動態路由:說簡單點,根據請求地址,從注冊中心選擇 合適的服務實例的列表,根據負載均衡的策略,從中選擇一個實例進行轉發
下面動態路由實現步驟:
1.依賴。由於注冊中心使用的是eureka,gateway需要注冊到eureka並且要獲取eureka上的其他服務的注冊信息,需要下面的依賴:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
2. yml配置:
spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true #開啟注冊中心路由功能,實現動態路由 # lower-case-service-id: true routes: - id: payment_routh #最好是服務名 uri: lb://cloud-payment-service #固定寫法: lb://服務名;lb表示啟用gateway的負載均衡功能
predicates: - Path=/payment/get/** - id: payment_routh2 uri: lb://cloud-payment-service predicates: - Path=/payment/myrule/**