Nacos源码分析十、配置动态刷新(3)

本文详细分析了Nacos配置动态刷新的工作流程,涉及NacosContextRefresher如何注册监听,配置变更时如何发布RefreshEvent事件,以及如何通过RefreshScope销毁并重新初始化bean。在配置变更时,Nacos首先更新环境属性,接着重新绑定配置属性对象,通过销毁和初始化确保使用最新配置。整个过程揭示了@RefreshScope在动态刷新中的关键作用。
摘要由CSDN通过智能技术生成

前文提到RefreshScope中维护了一个map缓存,缓存的内容是包装原bean的BeanLifecycleWrapper,这个包装类具备销毁能力。当新的配置更新通知来后,我们只要能找到RefreshScope去销毁了对应的bean,那么再次使用时cglib的proxy就会重新去获取target类实例,然后重新实例化。

回到NacosContextRefresher类,看一下注册监听的代码:

private void registerNacosListener(final String groupKey, final String dataKey) {
   String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey);
   Listener listener = listenerMap.computeIfAbsent(key,
         lst -> new AbstractSharedListener() {
            @Override
            public void innerReceive(String dataId, String group,
                  String configInfo) {
               refreshCountIncrement();
               nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo);
               // todo feature: support single refresh for listening
               applicationContext.publishEvent(
                     new RefreshEvent(this, null, "Refresh Nacos config"));
               if (log.isDebugEnabled()) {
                  log.debug(String.format(
                        "Refresh Nacos config group=%s,dataId=%s,configInfo=%s",
                        group, dataId, configInfo));
               }
            }
         });
   try {
      configService.addListener(dataKey, groupKey, listener);
   }
   catch (NacosException e) {
      log.warn(String.format(
            "register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey,
            groupKey), e);
   }
}

当有配置变更时发布RefreshEvent事件,这个事件是RefreshEventListener监听的:

@Override
public void onApplicationEvent(ApplicationEvent event) {
   
   if (event instanceof ApplicationReadyEvent) {
   
      handle((ApplicationReadyEvent) event);
   }
   else if (event instanceof RefreshEvent) 
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值