consul 默认配置修改后会自动刷新配置,但在某些时候我们需要获取修改我们修改之后的配置, 做自定义处理.
consul 在刷新配置之后 执行了EnvironmentChangeEvent事件, 我们只需要监听此事件即可.
// springcloud consul 源码
public synchronized Set<String> refreshEnvironment() {
// 获取刷新前所有配置
Map<String, Object> before = extract(
this.context.getEnvironment().getPropertySources());
// 实际执行刷新配置
addConfigFilesToEnvironment();
// 将新配置和老配置进行合并(若有更新则覆盖老配置,若无则保留老配置)
Set<String> keys = changes(before,
extract(this.context.getEnvironment().getPropertySources())).keySet();
this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys));
return keys;
}
事件监听代码
@EventListener(EnvironmentChangeEvent.class)
public void refreshed(EnvironmentChangeEvent event) {
Object source = event.getSource();
MutablePropertySources propertySources = ((AnnotationConfigServletWebServerApplicationContext) source)
.getEnvironment().getPropertySources();
// System.out.println(event.getKeys());
// Set<String> keys = event.getKeys();
propertySources.forEach(str -> {
// todo do something 此处即为项目所有配置信息
});
System.out.println("事件执行-- EnvironmentChangeEvent");
}
参考链接: https://blog.csdn.net/dbqb007/article/details/105407639