Apollo學習(六):自定義Meta Server地址定位邏輯

說明

在之前的一篇博文《Apollo學習(二): Java客戶端使用》中,我簡單地總結了Apollo配置中心的java客戶端使用方法,其中有幾個重要步驟,如確定項目的AppId,設置Meta Server的地址,設置本地緩存路徑的地址等。
在之前的博文中,對Meta Server地址的設定是通過項目內的app.properties配置文件和系統配置環境參數來進行設置的,這種方式在實際使用中,有很多個項目要接入配置中心,在每個項目中配置Meta Server的地址是十分不便的。在本篇博文中,我將根據官方文檔的介紹,創建自定義的Meta Server地址定位邏輯,以jar包的形式,方便多個項目配置使用。

正文

根據文檔介紹,Apollo提供了MetaServerProvider接口,通過實現此接口來定義地址提供邏輯。並且使用方式使用了典型的Java Service Loader模式。

注意,使用該模式後,必須在在 resources 下創建 META-INF/services/ com.ctrip.framework.apollo.core.spi.MetaServerProvider 文件,寫入自定義實現 MetaServerProvider 的全類名。

以下是我的實現類,首先在resources下創建apollo-env.porperties配置文件,該文件配置了各個環境的Meta Server的地址。在獲取時,首先會從Java System Property中獲取,若獲取值不爲空,則直接返回,否則從配置文件中獲取

public class CustomMetaServerProvider implements MetaServerProvider {

    private static final int ORDER = Ordered.HIGHEST_PRECEDENCE;
    private static final Map<Env, String> ENVMAP = new ConcurrentHashMap<>(16);

    public CustomMetaServerProvider() {
        initProperties();
    }

    public void initProperties() {
        Properties properties = ResourceUtils.readConfigFile("apollo-env.properties", null);
        properties.entrySet().forEach(entry -> {
            String envStr = (String) entry.getKey();
            String serverUrl = (String) entry.getValue();
            Env env = Env.fromString(envStr.substring(0, envStr.indexOf("_")));
            ENVMAP.put(env, serverUrl);
        });
    }

    @Override
    public String getMetaServerAddress(Env env) {
        String url = System.getProperty("apollo.meta");
        if (!Strings.isNullOrEmpty(url)) {
            return url;
        }
        url = getServerAddress(env);
        return url;
    }

    private String getServerAddress(Env env) {
        return ENVMAP.get(env);
    }

    @Override
    public int getOrder() {
        return ORDER;
    }
}

注意,Apollo在運行時會按照順序遍歷所有的MetaServerProvider,直到獲取到一個非空的Meta Server地址。因此,在實現了自定義獲取方式後,要定義它的Order,值越小優先級越大,所以這裏我配置了最高優先級

最後,我們可以將該項目打包成jar包的方式,因爲該項目依賴了apollo-client,所以客戶端在使用是可以直接依賴這個jar即可。


項目源碼:https://github.com/Edenwds/apollo_docker
參考資料:
https://github.com/ctripcorp/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java

https://github.com/ctripcorp/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章