在上一篇中,虽然实现了分布式配置中心,但也存在明显的缺陷,假如我修改了配置文件想去刷新读取配置,那么只能通过重启服务去实现,在项目已经上线的情况,这种方式是不可取的。因此本篇介绍Spring Cloud Bus组件,能够实现在不重启服务的前提下通过请求接口去实时刷新配置信息。
(一)对config-server工程进行改进
要使用Spring Cloud Bus消息总线,需要引入spring-cloud-starter-bus-amqp
以及spring-boot-starter-actuator
,由于这两个依赖已存在父pom.xml中,因此这里不需再引入。同时bus消息总线会用到RabbitMQ中间件,所以必须安装它;另外,也支持Kafka中间件,整合过程差不多,这里不多做介绍。
接着在config-server服务的application.yml中添加bus消息总线配置信息以及开放actuator的bus-refresh端点(SpringBoot2.x版本将基本的一些端点都整合到actuator了,所以需要用到这些端点时,需要配置开放):
#工程端口号
server:
port: 8888
#eureka注册中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
#配置rabbitmq信息,git的配置仓库地址、账号以及密码(不设置权限时可不配置账号密码,或者可以对账号密码加密与解密)
spring:
application:
name: config-server #工程名
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
cloud:
config:
server:
git:
uri: https://gitee.com/huijunzeng/configServer
search-paths: /config-rep #文件路径
#开放actuator的bus-refresh端点
management:
endpoints:
web:
exposure:
include: bus-refresh
(二)对config-client工程进行改进
在用到@Value的controller层的头部加上此注解 @RefreshScope
,使其能获取刷新后的信息
配置gitee码云上的server-client服务的配置文件server-client.yml:
依次启动eureka-server、config-server以及config-client工程,然后访问http://localhost:6001/getRomteConfigurationFromGit,可看到读取的内容:
然后修改gitee码云上的server-client服务的配置文件server-client.yml,将from: config-client-1.0
改为from: config-client-2.0
:
之后用postman发送post请求http://localhost:8888/actuator/bus-refresh,之前的SpringBoot1.x版本用的是http://localhost:8888/bus/refresh(请注意这个区别)
会看到config-client服务的控制台重新去拉取配置文件:
最后访问http://localhost:6001/getRomteConfigurationFromGit,可看到读取的是修改后的最新内容:
由此可见,通过bus消息总线实现了配置信息的动态刷新
本篇完结!
github代码地址:https://github.com/huijunzeng/springCloudDemo.git