微服务之Nacos配置中心源码解析(二)

Nacos配置中心源码解析

源码入口

ConfigFactory.createConfigService

ConfigService configService = NacosFactory.createConfigService(properties);
String  content = configService.getConfig(dataId,groupId,3000);

通过Factory构造ConfigService

装饰器模式MetricsHttpAgent包装http请求,增加了监控

agent->代理 http的方式发起请求 clientWorker ->具体的工作有关

NacosConfigService.NacosConfigService

this.agent = new MetricsHttpAgent(new ServerHttpAgent(properties));
this.agent.start();
this.worker = new ClientWorker(this.agent, this.configFilterChainManager, properties);
  • 创建了一个httpAgent的代理 ->发起http请求

  • 创建了一个clientWorker->异步线程(定时任务)

this.executor.scheduleWithFixedDelay(new Runnable() {
   public void run() {
       try {
           ClientWorker.this.checkConfigInfo();
      } catch (Throwable var2) {
           ClientWorker.LOGGER.error("[" + agent.getName() + "] [sub-check] rotate check error", var2);
      }

  }
}, 1L, 10L, TimeUnit.MILLISECONDS);

长轮询时请求很多怎么办?

分批处理

public void checkConfigInfo() {
   //分任务
   int listenerSize = ((Map)this.cacheMap.get()).size();
   //向上取整
   int longingTaskCount = (int)Math.ceil((double)listenerSize / ParamUtil.getPerTaskConfigSize());
   if ((double)longingTaskCount > this.currentLongingTaskCount) {
       for(int i = (int)this.currentLongingTaskCount; i < longingTaskCount; ++i) {
           //要判断任务是否执行 这块需要好好想想 任务列表现在是无序的 变化过程可能有问题
           this.executorService.execute(new ClientWorker.LongPollingRunnable(i));
      }

       this.currentLongingTaskCount = (double)longingTaskCount;
  }

}

检查本地配置 监听->

检查缓存的MD5

检查文件的更新时间

ClientWorker.this.checkLocalConfig(cacheData);
if (cacheData.isUseLocalConfigInfo()) {
  cacheData.checkListenerMd5();
}

检查远程

List<String> changedGroupKeys = ClientWorker.this.checkUpdateDataIds(cacheDatas, inInitializingCacheList);
Iterator var16 = changedGroupKeys.iterator();

groupId+dataId+tenant远程检查

ClientWorker.this.getServerConfig(dataId, group, tenant, 3000L);
void checkListenerMd5() {
   Iterator var1 = this.listeners.iterator();

   while(var1.hasNext()) {
       ManagerListenerWrap wrap = (ManagerListenerWrap)var1.next();
       if (!this.md5.equals(wrap.lastCallMd5)) {
           this.safeNotifyListener(this.dataId, this.group, this.content, this.md5, wrap);
      }
  }

}

获取配置

先去本地获取,如果没有再去远程拿配置

content = LocalConfigInfoProcessor.getFailover(this.agent.getName(), dataId, group, tenant);
if (content != null) {
   cr.setContent(content);
} else {
       content = this.worker.getServerConfig(dataId, group, tenant, timeoutMs);
     
}

 

转载于:https://www.cnblogs.com/java333/p/11306523.html

你可能感兴趣的:(微服务之Nacos配置中心源码解析(二))