Spring Cloud Config 簡介
What
- 配置管理工具包。
- 集中化管理集群配置。
- 提供分散式系统和微服務集中化的外部配置。
- 使用GIT來儲存配置訊息,本身就擁有對微服務應用配置訊息的版本管理。
- 實現了對服務端(Server)以及客戶端(Client)中環境變數和屬性設置的抽象化。
Why
- 方便服務配置文件統一管理:微服務越來越龐大,此時服務配置的管理會變得越複雜。
- 不同環境不同配置:一個應用中不會只有代碼,還需要連接資源和其他應用,經常會需要外部配置去調整。
- 系統的可伸縮、可擴充套件性好:微服務的隨著微服務框架的引入,微服務數量就會在產品中不斷增加。
- 運行期間動態自動刷新調整配置:起初微伺服器各自管各自的配置,在開發階段並沒什麼問題,但到了生產環境管理上就會有一定的困難度,如果要大規模更新某項配置,困難就可想而知。
Feature
- 中心化、版本控制、支援動態更新和語言獨立。
- 提供服務端和客戶端支援。
- 基於Spring環境,實現了與Spring應用無縫整合。
- 可用於任何語言開發的程式。
- 預設實現基於Git倉庫(也支援SVN),從而可以進行配置的版本管理。
Flow
- 流程說明:
1. 基於Git的WebHook,配置變更觸發server端refresh。
2. Server端接收到請求併發送給Spring Cloud Bus。
3. Spring Cloud Bus接到訊息並通知給客戶端。
4. 客戶端接收到通知,請求Server端獲取最新配置。
Implementation
實作基本架構圖:
1. 透過 Spring Initializr 建立 config-server project 以及 config-client project。
首先,先建立 config-server project
再來,建立 config-client project,因為 refresh(架構圖) 的關係,dependencies 需加上 Actuator。
建立完成之後,打開 Intellij 將兩包專案開啟。
2. config-server
POM.xml
有一個dependencies 為 spring-cloud-config-server
ConfigServerApplication.java
加上 @EnableConfigServer 就知道是為spring boot 裡面的 config-server
application.properties
設定 server.port
bootstrap.properties
因為要設定 config server detail 所以需加入一個 bootstrap.properties(此properties 會先被讀取)
config-server 基本設定完成後,待會 convert config-server into a git repository。
3. config-client
MessageResource.java
建立一個RestController 去mapping "/rest" 裡面的 message 會從Git 讀取。
application.properties
設定server.port = 8081,因為8080已經給config-server使用。
bootstrap.properties
application name: 用來讓server 能區別出是哪一個properties; config.uri: 與server端設定的port 號一致。
4. Convert whole project into git(config-server project)
config-client.properties
與上方bootstrap.properties 裡面application.name=config-client 相對應的properties檔。
git init
將config-client.properties commit 至 git
以上設定完成後,將 config-server 以及 config-client run 起來
成功 run 起config-server 及 config-client 後,localhost:8081/rest/message
config-client 先預設的 Default Hello(表示目前沒有任何對server的存取)。
加上@RefreshScope
重新 run config-client
因在config-client 裡的 bootstrap.properties 有設定讓 config-server 去讀取 config-client.properties,所以
透過 localhost:8081/rest/message 後的行為,server 則自動去 git 抓取 config-client.properties 回返至畫面上。
5. 更新 config-client.properties 並推至 Git
6. 透過 postman 觸發 spring cloud config 的 refresh 機制。
7. 重整畫面 localhost:8081/rest/message
透過 refresh 機制,提醒了config-client 有 properties 更新需跟 config-server 要最新的配置檔,再透過
server 去 Git 讀取最新的檔案。
Conclusion
Spring Cloud Config 配置中心是原生的配置中心,後端儲存支持豐富(例如:Git. SVN. Vault. 本地儲存)
但整體的機制以及運作比較繁瑣和麻煩,加上沒有介面管理,依賴性繁多(例如:若使用Git必須搭建GitLab; 若需實現配置批量
更新還需藉助Spring Cloud Bus,依賴 RabbitMQ),所以功能還達不到生產級的階段,目前只能在小規模的環境下使用。
參考資料:
https://www.youtube.com/watch?v=b2ih5RCuxTM
https://www.twblogs.net/a/5c65bee2bd9eee06ef379969
http://www.ityouknow.com/springcloud/2017/05/22/springcloud-config-git.html