微服务架构下通常使用统一配置中心(例nacos、Apollo)的动态配置方案,若项目是一个单独的springboot服务可使用以下轻量化的方式
spring boot结合actuator
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
暴露刷新配置的接口
修改配置文件,暴露出刷新配置的接口
@Value搭配@RefreshScope
触发刷新配置
启动项目后,修改配置文件中的值,请求刷新配置的接口 http://localhost:8080/actuator/refresh
效果
被@Value标注的成员变量值已经修改
源码
调用刷新配置的接口将会执行到以下方法
org.springframework.cloud.context.refresh.ContextRefresher#refresh
解读:先从容器上下文中获取当前的environment(留作比较),读取最新配置信息并更新到上下文中,对比配置差异,发布事件
自定义触发配置刷新
经源码分析refresh方法的调用者有两个,其中第一个便是上述actuator触发的方式。
而第二个是由监听器触发的,它基于spring的事件发布机制,当监听到RefreshEvent事件,会执行ContextRefresher#refresh
方法
org.springframework.cloud.endpoint.event.RefreshEventListener#onApplicationEvent
因此可以通过从spring容器中获取ContextRefresher
类型的bean,直接调用其refresh方法,或者基于spring事件机制发布RefreshEvent事件,这两种方式都可达到刷新配置的目的