004-spring cloud alibaba之gateway网关-负载均衡

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:'*'
相关推荐
beibeix20156 小时前
CppMicroServices 核心概念:动态服务注册与模块化系统
微服务·mitk
微三云 - 廖会灵 (私域系统开发)6 小时前
电商系统从单体到微服务拆分实践:拆什么、怎么拆、拆完后怎么办
微服务·云原生·架构
guslegend10 小时前
领域驱动设计,微服务设计为什么要选择DDD?
微服务·云原生·架构
VortMall12 小时前
全维度打磨细节体验,赋能商城稳定有序运营|VortMall 微服务商城 v1.3.11 版本发布
java·微服务·云原生·架构·商城系统·开源商城·vortmall
豆瓣鸡1 天前
Guava RateLimiter 限流实战:从令牌桶原理到 Nacos 动态配置
spring boot·微服务·nacos·guava
Wang's Blog2 天前
Go-Zero项目开发10: 微服务治理中心实现原理分析
开发语言·微服务·golang
xexpertS2 天前
分布式系统过载治理:如何通过较小服务控制请求节奏
微服务·自动化
爱学习的小可爱卢2 天前
SpringCloud——微服务实战:OpenFeign与Nacos服务调用详解
spring·spring cloud·微服务
吴声子夜歌2 天前
MongoDB 4.x——微服务入门
java·mongodb·微服务
阿标在干嘛3 天前
从HTTP到WebSocket:招投标信息实时推送系统的协议选型与架构设计
大数据·微服务·架构