当修改了Nacos配置的时候会自动刷新本地项目配置,来实现配置动态更新。
实现思路是当Spring项目启动的时候,会注册一个Listener监听器,在监听到配置发生变化的时候发布一个RefreshEvent事件,接下来利用Spring框架本身的内容刷新功能ContextRefresher来完成配置的刷新。
监听Spring项目启动
public class NacosContextRefresher implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private Map<String, Listener> listenerMap = new ConcurrentHashMap(16);
// SpringBoot启动的时候会发布该事件ApplicationReadyEvent
public void onApplicationEvent(ApplicationReadyEvent event) {
if (this.ready.compareAndSet(false, true)) {
this.registerNacosListenersForApplications();
}
}
注册Nacos的监听器Listener
注册一个监听器,当配置发生变化的时候发布一个Spring的内容刷新事件RefreshEvent
执行链:
this.registerNacosListenersForApplications()->
this.registerNacosListener(nacosPropertySource.getGroup(), dataId)->
private void registerNacosListener(final String group, final String dataId) {
// Lambda注册一个Listener事件
Listener listener = (Listener)this.listenerMap.computeIfAbsent(dataId, (i) -> {
return new Listener() {
public void receiveConfigInfo(String configInfo) {