SpringCloud配置中心源碼解讀

PropertySourceLocator接口

 

通過這個接口我們可以通過代碼動態的向Environment中添加PropertySource

Environment:Spring抽象了一個Environment來表示Spring應用程序環境配置,它整合了各種各樣的外部環境,並且提供統一訪問的方法(getProperty(String key))。

 

 

locate方法有兩個實現類,分別是配置中心config-server和讀取配置的客戶端config-client

 

PropertySource:PropertySource是一個抽象類,它包含一個source和一個name。source可以是map或其他,通常是一組鍵值對。 可以粗略理解爲一個配置源。

 

PropertySourceBootstrapConfiguration引導配置類

PropertySourceBootstrapConfiguration(springcloud-context包中)引導配置類中引入了上上述PropertySourceLocator接口

 

spring cloud有引導機制,在spring cloud-context中有spring.factories引導文件,該文件中就有PropertySourceBootstrapConfiguration類

 

該類中首先會獲取所有的PropertySourceLocator,並調用其locate方法,只有當propertySouceLocator有實現類時,它纔會獲取當前引導上下文的Environment,並在 insertPropertySources方法裏,把PropertySourceLocator的自定義屬性值添加到引導上下文的環境當中。

 

ConfigServer配置中心服務端

ConfigServer是配置中心的服務端,它負責統一管理配置,當我們以http://地址:端口號/{application}-{profile}.properties發送請求時會被EnvironmentController處理,我們來看一下EnvironmentController的源碼:

 

 

其中EnvironmentRepository是一個環境接口,有很多實現類,比如JdbcEnvironmentRepository,JGitEnvironmentRepository,RedisEnvironmentRepository,SvnKitEnvironmentRepository等,然後有一個方法定義爲:

findOne(String application, String profile, String label);

application:表示配置文件名稱;profile:表示配置文件的環境(test,pre,prod);label:一般表示分支(master等)

 

EnvironmentController核心代碼是getEnvironment;通過application profiles label這三個參數拿到對應的Environment ;但是這裏的Environment 不是springcloud-context中的Environment 

 

Environment :

ConfigServerBootstrapConfiguration:spring-cloud-config-server引導類,在spring-cloud-config-server中spring.factories中引入

 

 

 

 

ConfigServerBootstrapConfiguration中引入了EnvironmentRepositoryPropertySourceLocator類,EnvironmentRepositoryPropertySourceLocator實現了PropertySourceLocator,

在locate方法裏會調用EnvironmentRepository的findOne方法,此時會將SpringCloud的Environment類和Spring中的Environment相關聯

 

 

ConfigClient配置中心客戶端

當我們添加config-client時,啓動時會去客戶端請求遠程的配置進而加載至當前的Environment當中。我們先看一看它的spring.factories文件(spring-cloud-config-client):

 

與config-server端類似,我們可以發現其裝配了一個ConfigServicePropertySourceLocator的Bean,

 

 

ConfigServicePropertySourceLocator實現了PropertySourceLocator接口,然後通過rest服務請求服務端的EnvironmentController進而添加至當前的Environment

 

 

 

 

 

發佈了43 篇原創文章 · 獲贊 45 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章