一、业务场景
网关作为所有请求流量的入口,在实际生产环境中为了保证高可靠和高可用,尽量避免重启,需要用到动态路由配置,在网关运行过程中更改路由配置。
例如:因业务需要,新上线一个服务,而网关已对外提供服务,不能重启网关,但需要网关能路由到新服务来支撑新业务;
二、实现方式
方式1:编写动态路由实现类 :自定义实现类,继承路由基类;
方式2:编写监听 nacos 下发路由配置类;
三、优点
1、对路由信息进行统一管理,存储到自己的网关内存中去;
2、有阿里稳定团队维护nacos;
3、避免路由信息存储在redis缓存中,减轻缓存压力,线上网关节点个数很多,网关请求用redis增加压力;
四、实现 Demo
1、环境准备:
官网下载 nacos 1.1.4 版本源码,本地启动 nacos 服务;( git clone: https://github.com/alibaba/nacos ),注意本地idea要把VM参数设置成 nacos 单机模式:
-Dnacos.standalone=true ;
准备 一个测试用的 服务系统;
准备 spring cloud gateway 服务;如下图:
实现步骤:(这里只说明 spring cloud gateway 服务)
(1) pom 文件引入依赖
<dependencies>
<!-- nacos 配置 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
<!-- nacos 发现 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- webflux 编程方式 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<!-- 限流操作 存储到 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- 监控 健康检查, 监听 nacos 下发服务-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- 监控 健康检查, 监听 nacos 下发服务,建立长连接,客户端和 nacos 服务端 建立联系-->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>0.5.0</version>
</dependency>
</dependencies>
(2) 将服务启动,在nacos服务治理中心,配置管理新建配置并发布,这里 选用 json 格式,如下图
(3)接口测试
访问接口:
说明:
spring cloud gateway 服务 端口号: 1088 ;
当我们请求 网关端口,成功路由到 order-nacos 服务中
五.Gateway 整合 actuator 监控
步骤一: 添加依赖
<!--actuator 监控-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
步骤二: 配置文件添加配置信息
#开放所有页面节点 默认只开启了health、info两个节点
management:
endpoints:
web:
exposure:
include: '*'
步骤三:gateway 有改动,比如添加配置一个gateway实现效果如下