乾貨分享微服務spring-cloud(7.配置中心spring-cloud-config)

前言

讀者:對spring、spring boot有一定了解

難度:初中級,旨在快速應用於項目

參考文獻:網絡、書籍、官方文檔,有任何錯誤歡迎大家留言拍磚指正

實戰模擬源碼:https://github.com/yhqnh/demo-springcloud,使用spring-cloud dalston版本


Spring Cloud Config爲分佈式系統中的外部配置提供服務器和客戶端支持。使用Config Server,您可以在所有環境中管理應用程序的外部屬性。客戶端和服務器上的概念映射與Spring EnvironmentPropertySource抽象相同。Spring Cloud Config支持在Git, SVN和本地存放配置文件,使用Git或者SVN存儲庫可以很好地支持版本管理,Spring默認配置是使用Git存儲庫,因此它輕鬆支持標籤版本的配置環境,以及可以訪問用於管理內容的各種工具。

7.1.    服務器端

新建spring boot項目demo-springcloud-config-server,新建啓動ConfigServerApplication@EnableConfigServer開啓配置中心功能

image.png

項目依賴spring-cloud-config-server對配置中心支持

image.png

配置文件application.properties,讀者自行填上自己的github賬號和密碼以便訪問配置地址https://github.com/yhqnh/spring-cloud-demo-config-server-git.git

image.png

 

Github配置地址https://github.com/yhqnh/spring-cloud-demo-config-server-git.git是公開的,並且項目下面創建了config-repo目錄,創建了四個配置文件project.properties,

project-dev.properties,

project-test.properties,

project-prod.properties

分別配置了

github=github-default-1.0

github=github-dev-1.0

github=github-test-1.0

github=github-prod-1.0

image.png

Spring cloud config配置信息的URL與配置文件的映射關係如下所示:

/{application}/{profile}[/{label}]

/{application}-{profile}.yml

/{label}/{application}-{profile}.yml

/{application}-{profile}.properties

/{label}/{application}-{profile}.properties

上面的url會映射{application}-{profile}.properties對應的配置文件,其中{label}對應git上不同的分支,默認爲master。啓動應用用瀏覽器訪問http://localhost:5551/project/dev映射成project-dev.properties以此訪問dev配置文件

image.png

 

7.2.    客戶端

新建spring boot 項目並命名爲demo-springcloud-config-client,創建啓動類ConfigClientApplication

image.png

配置文件bootstrap.properties,多環境配置spring.profiles.active=dev表示激活dev配置

image.png

本地新建配置文件application-dev.properties

image.png

新建YhqController,獲取配置文件我們採用兩種方式,一種@Value,一種Environment

image.png

關鍵依賴

image.png

啓動應用瀏覽器訪問http://localhost:5552/getConfigFromValuehttp://localhost:5552/getConfigFromEnviroment讀取之前本地配置文件變量值github-local-1.0

image.png

image.png

通過前面講的加載順序7優先於8,我們做一個驗證。設置bootstrap.propertiesspring.cloud.config.uri值讓配置從上面搭建的配置服務端獲取配置

image.png

啓動應用瀏覽器http://localhost:5552/getConfigFromValuehttp://localhost:5552/getConfigFromEnviroment獲取到了github-dev-1.0而並非github-local-1.0image.png

image.png

下面 我們來實現動態刷新github的值,動態刷新依賴於/refresh端點,添加依賴spring-boot-starter-actuator爲我們提供刷新端點/refresh並修改bootstrap.properties配置management.security.enabled=false來關閉springboot 1.5.X 以上默認開通的安全認證訪問/refresh端點。

YhqController添加刷新註解@RefreshScope啓動應用訪問http://localhost:5552/getConfigFromValuehttp://localhost:5552/getConfigFromEnviroment返回結果如上圖github-dev-1.0

這時我們修改配置中心服務端的github值爲github-dev-1.0-modify

image.png

再次訪問http://localhost:5552/getConfigFromValuehttp://localhost:5552/getConfigFromEnviroment返回結果還是如上圖github-dev-1.0

怎麼配置沒有動態刷新,這時需要post方式訪問http://localhost:5552/refresh端點

再次訪問http://localhost:5552/getConfigFromValuehttp://localhost:5552/getConfigFromEnviroment看看配置是否動態生效

image.png

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