disconf原理 「入坑」指南

以前有了解過disconf,也知道它是基於zookeeper來作的,可是對於其運行原理不太瞭解,趁着週末,debug下源碼,也算是不枉費週末大好時光哈 :) 。關於這篇文章,筆者主要是參考disconf源碼和官方文檔,如有不正確地方,感謝評論區指正交流~前端

disconf是一個分佈式配置管理平臺(Distributed Configuration Management Platform),專一於各類 分佈式系統配置管理 的通用組件/通用平臺, 提供統一的配置管理服務,是一套完整的基於zookeeper的分佈式配置統一解決方案。disconf目前已經被多個公司在使用,包括百度、滴滴出行、銀聯、網易、拉勾網、蘇寧易購、順豐科技 等知名互聯網公司。disconf源碼地址 https://github.com/knightliao/disconf ,官方文檔 https://disconf.readthedocs.io/zh_CN/latest/java

目前disconf包含了 客戶端disconf-Client和 管理端disconf-Web兩個模塊,均由java實現。服務依賴組件包括Nginx、Tomcat、Mysql、ZooKeeper,nginx提供反向代理(disconf-web是先後端分離的),Tomcat是後端web容器,配置存儲在mysql上,基於zookeeper的wartch模型,實時推送。注意,disconf優先讀取本地文件,disconf只支持應用對配置的讀操做,經過在disconf-web上更新配置,而後由zookeeper通知到服務實例,最後服務實例去disconf-web端獲取最新配置並更新到本地。node

 

disconf 功能特色:mysql

  • 支持配置(配置項/配置文件)分佈式管理
  • 配置發佈統一化
    • 配置發佈、更新統一化,同一個上線包 無須改動配置 便可在 多個環境中(RD/QA/PRODUCTION) 上線
    • 配置更新自動化:用戶在平臺更新配置,使用該配置的系統會自動發現該狀況,並應用新配置。特殊地,若是用戶爲此配置定義了回調函數類,則此函數類會被自動調用
  • 上手簡單,基於註解或者xml配置方式

功能特色描述圖nginx

 

disconf 架構圖git

 

分析disconf,最好是在本地搭建一個disconf-web環境,方便調試代碼,具體步驟可參考官方文檔,使用disconf-client,只須要在pom引入依賴便可:github

<dependency>
    <groupId>com.baidu.disconf</groupId>
    <artifactId>disconf-client</artifactId>
    <version>2.6.36</version>
</dependency>

對於開發人員來講,最多接觸的就是disconf-web配置和disconf-client了,disconf-web配置官方文檔已經很詳細了,這裏就來不及解釋了,抓緊上車,去分析disconf-client的實現,disconf-client最重要的內容就是disconf-client初始化流程配置動態更新機制。disconf的功能是基於Spring的(初始化是在Spring的BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry開始的,配置動態更新也是要更新到Spring IoC中對應的bean),因此使用disconf,項目必須基於Spring。web

 

1 disconf-client 初始化流程

關於disconf-client的初始化,聯想到Spring IoC流程,咱們先不看代碼,能夠猜測一下其大體流程,disconf-client首先須要從disconf服務端獲取配置,而後等到IoC流程中建立好對應的bean以後,將對應的配置值設置到bean中,這樣基本上就完成了初始化流程,其實disconf的初始化實現就是這樣的。
 
disconf-client的初始化開始於BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(Spring IoC初始化時,對於BeanDefinitionRegistryPostProcessor的實現類,會調用其postProcessBeanDefinitionRegistry方法),disconf的DisconfMgrBean類就是BeanDefinitionRegistryPostProcessor的實現類,DisconfMgrBean類的bean配置在哪裏呢?其實就是disconf.xml中的配置,該配置是必須的,示例以下:
<!-- 使用disconf必須添加如下配置 -->
<bean id="disconfMgrBean" class="com.baidu.disconf.client.DisconfMgrBean"
      destroy-method="destroy">
    <property name="scanPackage" value="com.luo.demo"/>
</bean>
<bean id="disconfMgrBean2" class="com.baidu.disconf.client.DisconfMgrBeanSecond"
      init-method="init" destroy-method="destroy">
</bean>

 
DisconfMgrBean#postProcessBeanDefinitionRegistry方法主要作的3件事就是掃描(firstScan)、註冊DisconfAspectJ 和 bean屬性注入。sql

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    // scanPackList包括disconf.xml中DisconfMgrBean.scanPackage
    List<String> scanPackList = StringUtil.parseStringToStringList(scanPackage, SCAN_SPLIT_TOKEN);

    // 1. 進行掃描
    DisconfMgr.getInstance().setApplicationContext(applicationContext);
    DisconfMgr.getInstance().firstScan(scanPackList);

    // 2. register java bean
    registerAspect(registry);
}

 

1.1 firstScan

firstScan操做主要是加載系統配置和用戶配置(disconf.properties),進行包掃描併入庫,而後獲取獲取數據/注入/Watch。
protected synchronized void firstScan(List<String> scanPackageList) {
    // 導入配置
    ConfigMgr.init();
    
    // registry
    Registry registry = RegistryFactory.getSpringRegistry(applicationContext);

    // 掃描器
    scanMgr = ScanFactory.getScanMgr(registry);

    // 第一次掃描併入庫
    scanMgr.firstScan(scanPackageList);

    // 獲取數據/注入/Watch
    disconfCoreMgr = DisconfCoreFactory.getDisconfCoreMgr(registry);
    disconfCoreMgr.process();
}

進行包掃描是使用Reflections來完成的,獲取路徑下(好比xxx/target/classes)某個包下符合條件(好比com.luo.demo)的資源(reflections),而後從reflections獲取某些符合條件的資源列表,以下:json

/**
 * 掃描基本信息
 */
private ScanStaticModel scanBasicInfo(List<String> packNameList) {
    ScanStaticModel scanModel = new ScanStaticModel();

    // 掃描對象
    Reflections reflections = getReflection(packNameList);
    scanModel.setReflections(reflections);

    // 獲取DisconfFile class
    Set<Class<?>> classdata = reflections.getTypesAnnotatedWith(DisconfFile.class);
    scanModel.setDisconfFileClassSet(classdata);

    // 獲取DisconfFileItem method
    Set<Method> af1 = reflections.getMethodsAnnotatedWith(DisconfFileItem.class);
    scanModel.setDisconfFileItemMethodSet(af1);

    // 獲取DisconfItem method
    af1 = reflections.getMethodsAnnotatedWith(DisconfItem.class);
    scanModel.setDisconfItemMethodSet(af1);

    // 獲取DisconfActiveBackupService
    classdata = reflections.getTypesAnnotatedWith(DisconfActiveBackupService.class);
    scanModel.setDisconfActiveBackupServiceClassSet(classdata);

    // 獲取DisconfUpdateService
    classdata = reflections.getTypesAnnotatedWith(DisconfUpdateService.class);
    scanModel.setDisconfUpdateService(classdata);
    
    return scanModel;
}
View Code
獲取到資源信息(好比DisconfFile 和DisconfFileItem )以後,讀取DisConfFile類及其對應的DisconfFileItem信息,將它們放到disconfFileItemMap中,最後將這些信息存儲到倉庫DisconfCenterStore。這部分邏輯在ScanMgrImpl.firstScan方法中,總體邏輯仍是比較清晰的,這裏就不貼代碼了。
 
掃描入庫以後,就該獲取數據/注入/Watch(DisconfCoreFactory.getDisconfCoreMgr()中邏輯)了。
public static DisconfCoreMgr getDisconfCoreMgr(Registry registry) throws Exception {
    FetcherMgr fetcherMgr = FetcherFactory.getFetcherMgr();
    
    // 不開啓disconf,則不要watch了
    WatchMgr watchMgr = null;
    if (DisClientConfig.getInstance().ENABLE_DISCONF) {
        // Watch 模塊
        watchMgr = WatchFactory.getWatchMgr(fetcherMgr);
    }
    return new DisconfCoreMgrImpl(watchMgr, fetcherMgr, registry);
}
public static WatchMgr getWatchMgr(FetcherMgr fetcherMgr) throws Exception {

    synchronized(hostsSync) {
        // 從disconf-web端獲取 Zoo Hosts信息,及zookeeper host和zk prefix信息(默認 /disconf)
        hosts = fetcherMgr.getValueFromServer(DisconfWebPathMgr.getZooHostsUrl(DisClientSysConfig
                                                                                   .getInstance()
                                                                                   .CONF_SERVER_ZOO_ACTION));
        zooPrefix = fetcherMgr.getValueFromServer(DisconfWebPathMgr.getZooPrefixUrl(DisClientSysConfig
                                                                                        .getInstance
                                                                                             ()
                                                                                        .CONF_SERVER_ZOO_ACTION));

        /**
         * 初始化watchMgr,這裏會與zookeeper創建鏈接,若是/disconf節點不存在會新建
         */
        WatchMgr watchMgr = new WatchMgrImpl();
        watchMgr.init(hosts, zooPrefix, DisClientConfig.getInstance().DEBUG);

        return watchMgr;
    }

    return null;
}
從disconf-web端獲取zk host和 zk prefix以後,會創建與zk的鏈接,而後就該從disconf-web端下載配置和watcher了,也就是disconfCoreMgr.process()邏輯。下載配置時disconf-client從disconf-web端獲取配置的全量數據(http鏈接),並存放到本地,而後解析數據,生成dataMap,dataMap是全量數據。而後將數據注入到倉庫中(DisconfCenterStore.confFileMap,類型爲Map<String, DisconfCenterFile>)。注意:這裏尚未將配置的值設置到bean中,設置bean值是在Spring的finishBeanFactoryInitialization流程作的,準確來講是在初始化bean DisconfMgrBeanSecond(bean配置在disconf.xml中),調用其init方法中作的。
 
在將值設置到倉庫以後,就該監聽對應配置了,這樣才能使用zk的watch機制,在zk上監聽的url格式爲 /disconf/boot-demo_1_0_0_0_rd/file/specific.properties ,若是該url對應的node不存在則新建,注意該node是persistent類型的。而後在該node下新建臨時節點,節點名字是discon-client的簽名,格式爲host_port_uuid,節點data爲針對該配置文件,disconf-client須要的配置項的json格式數據,好比"{"port":9998,"host":"192.168.1.104"}"。
 

1.2 註冊DisconfAspectJ

 往Spring中註冊一個aspect類DisconfAspectJ,該類會對@DisconfFileItem註解修飾的方法作切面,功能就是當獲取bean屬性值時,若是開啓了DisClientConfig.getInstance().ENABLE_DISCONF,則返回disconf倉庫中對應的屬性值,不然返回bean實際值。注意:目前版本的disconf在更新倉庫中屬性值後會將bean的屬性值也一同更改,因此,目前DisconfAspectJ類做用已不大,沒必要理會,關於該類的討論可參考issue DisconfAspectJ 攔截的做用?

1.3 bean屬性注入

bean屬性注入是從DisconfMgr.secondScan開始的:

protected synchronized void secondScan() {
    // 掃描回調函數,也就是註解@DisconfUpdateService修飾的配置更新回調類,該類需實現IDisconfUpdate
    if (scanMgr != null) {
        scanMgr.secondScan();
    }

    // 注入數據至配置實體中
    if (disconfCoreMgr != null) {
        disconfCoreMgr.inject2DisconfInstance();
    }
}
 
bean屬性注入經過獲取倉庫中對應的屬性值,而後調用setMethod.invoke或者field.set方法來設置,bean對應的boject是經過Spring來獲取的,也就是說,在獲取後bean已經初始化完成,只不過對應的屬性值還不是配置文件中配置的而已。若是程序中有2個類的@DisconfFile都是同一個配置文件,那麼這個時候獲取的bean是哪一個類的bean呢?關於這個能夠點擊issue DisconfFile用法諮詢,disconf目前只支持一個配置文件一個類的方式,不給兩個class同時使用同一個 "resources.properties",不然第二個是不生效的。

 

2 配置動態更新機制

disconf的配置動態更新藉助於zk的watch機制(watch機制是zk 3大重要內容之一,其他兩個是zk協議和node存儲模型)實現的,初始化流程會中會對配置文件註冊watch,這樣當配置文件更新時,會通知到discnof-client,而後disconf-client再從disconf-web中獲取最新的配置並更新到本地,這樣就完成了配置動態更新。
 
配置動態更新動做開始於DisconfFileCoreProcessorImpl.updateOneConfAndCallback()方法:
/**
 * 更新消息: 某個配置文件 + 回調
 */
@Override
public void updateOneConfAndCallback(String key) throws Exception {

    // 更新 配置
    updateOneConf(key);

    // 回調
    DisconfCoreProcessUtils.callOneConf(disconfStoreProcessor, key);
    callUpdatePipeline(key);
}
更新配置時,首先更新倉庫中值,而後更新bean屬性值,配置更新回調是用戶自定義的回調方法,也就是@DisconfUpdateService修飾的類。配置更新時流程是:
開發人員在前端更新配置 -> disconf-web保存數據並更新zookeeper -> zookeeper通知disconf-client -> discnof-client 從 disconf-web下載對應配置 -> 更新倉庫和bean屬性 -> 調用回調 -> 更新配置完成。
 

小結

disconf 做爲一個分佈式的配置管理平臺,文檔詳細,易於上手,動態配置更新,知足大多數場景的配置更新需求。美中不足的是,代碼有的地方有點臃餘,獲取配置時仍是全量獲取方式,目前還不支持多個類共用同一個 "resources.properties",多餘的DisconfAspectJ操做等。
 
使用disconf,最好的使用方式是基於它,將其改形成適合本公司或者項目組的工具,好比更方便的註解方式和回調方式等。
相關文章
相關標籤/搜索