本人最近在学习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]
复制代码
控制台日志:
按照如上配置就可以达到效果,在控制台日志方面也有相关体现。最后大家也可以尝试一波看看。