问题现象
使用@value 注解,配置实时更新,使用@ConfigurationProperties 注解配置无实时更新
解决方案
Apollo是支持@ConfigurationProperties自动更新配置的值的,但需要增加一些配置。
伪代码
@Component
public class ApolloRefreshConfig implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
// 监听 apollo 配置变化
@ApolloConfigChangeListener()
public void onChange(ConfigChangeEvent changeEvent) {
Set<String> changedKeys = changeEvent.changedKeys();
// 将识别到需要热更新的 key 找到对应的 bean,依赖refreshScope刷新
refreshScope.refresh("beanName");
}
}
具体的实现我已经封装好成 starter ,引入即可使用,操作方式也非常简单:
- 引入依赖
<dependency>
<groupId>io.github.izachwei</groupId>
<artifactId>apollo-config-spring-boot-starter</artifactId>
<version>1.0.4-RELEASE</version>
</dependency>`
- 在 @ConfigurationProperties bean 上添加注解 @ApolloConfigRefresh,开启配置热更新。
总结
源代码地址:https://github.com/izachwei/apollo-config-spring-boot-starter