一、背景
最近在学习Spring Cloud Gateway
,而咱们的路由配置默认状况下是写在配置文件中的,这样当咱们有一个新的服务接入时,须要批改配置文件,而后重启网关应用程序,那么咱们是否能够在不进行网关的状况下,动静的刷新路由信息呢?
二、解决方案
咱们晓得,nacos
是能够实现 配置的动静刷新 和 服务发现的。那么咱们将 Spring Cloud Gateway
的配置放到 nacos
上是否就能够实现动静的刷新路由呢?
通过测试发现是能够实现的。此处咱们通过 Spring Cloud Alibaba
技术来实现。
1、服务的注册和发现应用 Spring Cloud Alibaba Nacos
来实现。
2、网关应用 Spring Cloud Gateway
来实现。
论断: 其实只须要在 Spring Cloud Gateway
中整合 Spring Cloud Alibaba Nacos Config
,网关的路由配置就能够主动刷新了,不须要额定的编码。
三、实现性能
1、提供一个商品服务,对外提供一个 findAllProduct
的接口返回商品信息。
2、实现一个网关服务,内部服务的拜访,都先通过网关程序,而后调用到具体的服务。
3、网关服务 的路由配置信息须要能够动静的配置。
四、实现步骤
1、网关服务的实现
1、pom文件
<dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency></dependencies>
2、bootstrap.yml配置文件
spring: application: name: gateway-9201 cloud: nacos: discovery: # 配置 nacos 的服务地址 server-addr: localhost:8847 config: # nacos 配置服务的地址,前面的端口不能省,即便是80端口 server-addr: localhost:8847 # 加载 dataid 配置文件的后缀,默认是 properties file-extension: yml # 配置组,默认就是 DEFAULT_GROUP group: DEFAULT_GROUP # 配置命名空间,此处写的是 命名空间的id 的值,默认是 public 命名空间 # namespace: # data-id 的前缀,默认就是 spring.application.name 的值 prefix: ${spring.application.name} server: port: 9201
留神: 因为配置是搁置在 nacos
上,所以和Spring Cloud Alibaba Nacos Config
相干的配置须要搁置到 bootstrap.yml
配置文件中。
此处次要配置 nacos 的配置信息,不须要配置 网关的路由信息。
3、启动类
@SpringBootApplicationpublic class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class); }}
启动类上不须要额定别的注解。
4、nacos上网关的配置
spring: cloud: gateway: routes: - id: user-9202 uri: lb://product-9202 predicates: - Path=/user/** filters: - RewritePath=/user(?<segment>/?.*), $\{segment} - id: product-9203 uri: lb://product-9203 predicates: - Path=/product123/** filters: - RewritePath=/product123(?<segment>/?.*), $\{segment}
5、网关配置实现
至此网关程序就配置实现了,那么这样配置之后路由就能够动静的刷新了吗?是的。Spring Cloud Gateway
和Spring Cloud Alibaba nacos config
整合后就主动实现了配置的主动刷新性能。
2、商品服务的实现
商品服务就是简略的提供了一个 rest api
,而后注册到 nacos
上,比较简单,略。
五、实现成果
六、实现代码
https://gitee.com/huan1993/spring-cloud-alibaba-parent/tree/master/gateway-dynamic-refresh-route
七、参考文档
1、https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md