spring cloud 2.x版本 Gateway动态路由教程
摘要
本文采用的Spring cloud为2.1.8RELEASE,version=Greenwich.SR3
本文基于前面的几篇Spring cloud Gateway文章的实现。
参考
前言
写了几篇关于Spring Cloud Gateway的文章后发现,Gateway涉及的知识范围太广了,真是深刻体会了“一入Spring cloud深似海”。
现实生产环境中,使用Spring Cloud Gateway都是作为所有流量的入口,为了保证系统的高可用,尽量避免系统的重启,所以需要Spring Cloud Gateway的动态路由来处理。之前的文章《Gateway路由网关教程》提供的路由配置,在系统启动时候,会将路由配置和规则加载到内存当中,无法做到不重启服务就可以动态的新增、修改、删除内存中的路由配置和规则。
简单的动态路由实现
Spring Cloud Gateway源码中提供了GatewayControllerEndpoint类来修改路由配置,但是官方文档好像并没有做详细的使用说明,只是简单介绍了几个简单的api接口。感兴趣的小伙伴可以先查看官方文档(第11章节 Actuator API)。
引致官方文档:
The
/gateway
actuator endpoint allows to monitor and interact with a Spring Cloud Gateway application. To be remotely accessible, the endpoint has to be enabled and exposed via HTTP or JMX in the application properties.
1.1 添加相关pom依赖
在原来spring-gateway的基础上增加spring-boot-starter-actuator依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
1.2 在application.yml中增加配置
management:
endpoints:
web:
exposure:
include: "*"
配置说明:management.endpoints.web.exposure.include 暴露所有的gateway端点
1.3 启动服务
启动服务,访问http://localhost:8100/actuator/gateway/routes,这是我们可以看到所有的routes信息。image-20191102225203034.png我们也可以访问单个路由信息:http://localhost:8100/actuator/gateway/routes/CompositeDiscoveryClient_EUREKA-CLIENT
显示如下:image-20191102225853005.png