Spring Cloud Config是Spring Cloud團隊建立的一個全新項目,用來爲分佈式系統中的基礎設施和微服務應用提供集中化的外部配置支持,它分爲服務端與客戶端兩個部分。其中服務端也稱爲分佈式配置中心,它是一個獨立的微服務應用,用來鏈接配置倉庫併爲客戶端提供獲取配置信息、加密/解密信息等訪問接口;而客戶端則是微服務架構中的各個微服務應用或基礎設施,它們經過指定的配置中心來管理應用資源與業務相關的配置內容,並在啓動的時候從配置中心獲取和加載配置信息。Spring Cloud Config實現了對服務端和客戶端中環境變量和屬性配置的抽象映射,因此它除了適用於Spring構建的應用程序以外,也能夠在任何其餘語言運行的應用程序中使用。因爲Spring Cloud Config實現的配置中心默認採用Git來存儲配置信息,因此使用Spring Cloud Config構建的配置服務器,自然就支持對微服務應用配置信息的版本管理,而且能夠經過Git客戶端工具來方便的管理和訪問配置內容。固然它也提供了對其餘存儲方式的支持,好比:SVN倉庫、本地化文件系統。java
在本文中,咱們將學習如何構建一個基於Git存儲的分佈式配置中心,並對客戶端進行改造,並讓其可以從配置中心獲取配置信息並綁定到代碼中的整個過程。git
準備一個git倉庫,能夠在碼雲或Github上建立均可以。好比本文準備的倉庫示例:http://git.oschina.net/didispace/config-repo-demoweb
假設咱們讀取配置中心的應用名爲config-client
,那麼咱們能夠在git倉庫中該項目的默認配置文件config-client.yml
:spring
info: profile: default
config-client-dev.yml
:info: profile: dev
經過Spring Cloud Config來構建一個分佈式配置中心很是簡單,只須要三步:瀏覽器
config-server-git
,並在pom.xml
中引入下面的依賴(省略了parent和dependencyManagement部分):<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies>
@EnableConfigServer
註解,開啓Spring Cloud Config的服務端功能。@EnableConfigServer @SpringBootApplication public class Application { public static void main(String[] args) { new SpringApplicationBuilder(Application.class).web(true).run(args); } }
application.yml
中添加配置服務的基本信息以及Git倉庫的相關信息,例如:spring application: name: config-server cloud: config: server: git: uri: http://git.oschina.net/didispace/config-repo-demo/ server: port: 1201
到這裏,使用一個經過Spring Cloud Config實現,並使用Git管理配置內容的分佈式配置中心就已經完成了。咱們能夠將該應用先啓動起來,確保沒有錯誤產生,而後再嘗試下面的內容。服務器
若是咱們的Git倉庫須要權限訪問,那麼能夠經過配置下面的兩個屬性來實現; spring.cloud.config.server.git.username:訪問Git倉庫的用戶名 spring.cloud.config.server.git.password:訪問Git倉庫的用戶密碼
完成了這些準備工做以後,咱們就能夠經過瀏覽器、POSTMAN或CURL等工具直接來訪問到咱們的配置內容了。訪問配置信息的URL與配置文件的映射關係以下:架構
上面的url會映射{application}-{profile}.properties
對應的配置文件,其中{label}
對應Git上不一樣的分支,默認爲master。咱們能夠嘗試構造不一樣的url來訪問不一樣的配置內容,好比,要訪問master分支,config-client應用的dev環境,就能夠訪問這個url:http://localhost:1201/config-client/dev/master
,並得到以下返回:app
{ "name": "config-client", "profiles": [ "dev" ], "label": "master", "version": null, "state": null, "propertySources": [ { "name": "http://git.oschina.net/didispace/config-repo-demo/config-client-dev.yml", "source": { "info.profile": "dev" } }, { "name": "http://git.oschina.net/didispace/config-repo-demo/config-client.yml", "source": { "info.profile": "default" } } ] }