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/

目前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端獲取最新配置並更新到本地。

 

disconf 功能特點:

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

功能特點描述圖

 

disconf 架構圖

 

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

<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。

 

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屬性注入。

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獲取某些符合條件的資源列表,如下:

/**
 * 掃描基本信息
 */
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,最好的使用方式是基於它,將其改造成適合本公司或者項目組的工具,比如更方便的注解方式和回調方式等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM