本人最近在學習Spring Cloud Gateway但是發現網上的相關文章都沒有介紹其如何使用負載均衡策略,那麼本篇文章就給大家帶來如何使用Spring Cloud Gateway負載均衡策略。
至於如何搭建Spring Cloud Gateway服務各位讀者請自行百度,好了進入正題。
接下來給大家看一段配置:
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: 192.168.2.109:8848
config:
server-addr: 192.168.2.109:8848
file-extension: yml
gateway:
routes:
- id: business-account
uri: http://localhost:8081/business-account
predicates:
- Path=/account/get
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
- id: business-account
uri: http://localhost:8082/business-account/
predicates:
- Path=/account/get
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
複製程式碼
大家看到上面的配置是不是很熟悉,網上的文章都這麼配置的,配置就是根據uri+preficates->path進行構建請求報文,但是最終不會走Ribbon。那麼如何才能讓其走Ribbon負載均衡呢?通過檢視官網發現其有一個叫LoadBalancerClient過濾器,然後根據其說明lb://服務名則可以使用負載均衡,修改後的配置如下:
spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: 192.168.2.107:8848
config:
server-addr: 192.168.2.107:8848
file-extension: yml
gateway:
routes:
- id: business-account
uri: lb://business-account #lb://服務名
# uri: http://localhost:8081/business-account
predicates:
- Path=/account/get
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
- id: business-account
uri: lb://business-account
# uri: http://localhost:8082/business-account/
predicates:
- Path=/account/get
- After=2017-01-20T17:42:47.789-07:00[America/Denver]
複製程式碼
控制檯日誌:
按照如上配置就可以達到效果,在控制檯日誌方面也有相關體現。最後大家也可以嘗試一波看看。