spring gateway配合nacos实现负载均衡

1,注册服务到nacos

首先让所有服务都能被nacos给发现,具体教程:整合spring cloud+nacos

2,搭建gateway服务

然后我们建立一个服务,并引入spring gateway相关依赖

xml 复制代码
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>

⚠️ 重要 :Gateway必须使用WebFlux模型,若项目中存在spring-boot-starter-web依赖,需移除:

webflux和webmvc两套系统是冲突的。

3,配置路由规则

我们在配置文件中写上相应的路由配置,假设我们已经配置了一个名为demo的服务

yml 复制代码
    gateway:
      routes:
        - id: demo
          uri: lb://demo
          predicates:
            - Path=/demo/**
          filters:
            - StripPrefix=1

其中,lb: 这个配置代表负载均衡,StripPrefix 代表要去掉的地址数,意味着在我进行路由转发的时候要去掉/demo。

4. 多实例负载均衡测试

接下来我们在idea里面找到服务列表,右键现有demo服务->编辑所选配置->修改选项->允许多个实例

再编辑这个实例的配置,用同样的找到添加虚拟机选项设置,并写上-Dserver.port=新端口号,我们就有两台同样的服务了。

我的网关服务部署在8888端口,我们提前写好相关接口/user/test

接下来我来访问4次http://localhost:8888/demo/user/test

可以看到两台服务各打印了两次

相关推荐
半梦半醒*1 天前
ansible中配置并行以及包含和导入
linux·运维·ssh·ansible·负载均衡
考虑考虑1 天前
org.springframework.boot.autoconfigure.AutoConfiguration.imports文件
spring boot·后端·spring
杨杨杨大侠1 天前
手搓责任链框架 4:链式构建
java·spring·github
原来是好奇心1 天前
Spring Boot 事务失效的八大原因及解决方案详解
spring·springboot·事务
laoma-cloud1 天前
Web 集群高可用全方案:Keepalived+LVS (DR) 负载均衡 + Apache 服务 + NFS 共享存储搭建指南
运维·负载均衡·高可用·web集群
伍树明1 天前
本地搭建搜索Agent(SpringAI + RAG + SearXNG + MCP)
java·spring·agent·mcp
杨杨杨大侠1 天前
手搓责任链框架 5:执行流程
java·spring·github
Pierre_1 天前
通过SpringCloud Gateway实现API接口镜像请求(陪跑)网关功能
spring·spring cloud·gateway
Go away, devil1 天前
如何在SptingBoot项目中引入swagger生成API文档
java·开发语言·spring boot·spring
无名指的等待7121 天前
Spring AI Graph工作流案例
java·人工智能·spring