gateway负载均衡
主要内容:使用自动负载均衡能力/手动负载均衡。启动多个user服务。让gateway自动选择需要路由到哪个user服务中。这其中有两点需要关心
- 自动负载能力:一般采用轮询的方式调用user服务
- gateway查找规则:user服务注册到nacos上gateway会按照注册的服务名称自动映射到对应的服务
手动负载均衡同样可以实现上面的能力还可以避免暴露nacos服务注册的服务名
- 自动负载均衡
- 手动负载均衡
1、gateway自动负载均衡
1.1 启动服务情况
启动两个user服务
| 服务 | 端口 |
|---|---|
| user | 9001 |
| user | 9002 |
| gateway | 9999 |
服务都注册到nacos上面

1.2 gateway配置文件
yaml
server:
port: 9999
spring:
application:
name: gateway-service
cloud:
nacos:
discovery:
server-addr: 10.106.114.1:8848
gateway:
discovery:
locator:
enabled: true
其中gateway.discovery.locator.enabled=true就是开启自动负载功能。此时如何访问:http://localhost:9999/user/user/hello 就能够自动访问到user服务。前面一个/user/是在找nacos上面的服务,后面一个/user/是我们前面配置的context-path。所以我们可以去掉context-path然后重启user,这样访问路径就变成:http://localhost:9999/user/hello
1.2.1 user服务配置文件变更
变更前
yaml
server:
port: 9001
servlet:
context-path: /user/
spring:
application:
name: user
cloud:
discovery:
server-addr: 127.0.0.1:8848
management:
endpoint:
web:
exposure:
include:'*'
变更后
yaml
server:
port: 9001
spring:
application:
name: user
cloud:
discovery:
server-addr: 127.0.0.1:8848
management:
endpoint:
web:
exposure:
include:'*'
这种自动负载会暴露我们nacos注册的服务名字。还可以使用手动负载
2、手动负载均衡
修改gateway配置文件
yaml
server:
port: 9999
spring:
application:
name: gateway-service
cloud:
nacos:
discovery:
server-addr: 10.106.114.1:8848
gateway:
discovery:
locator:
enabled: false
routes:
- id: user
uri: lb://user
predicates:
- Path=/cjxz/**
filters:
- StripPrefix=1 # 去掉第一个路径:/cjxz/
management:
endpoint:
web:
exposure:
include:'*'