1. 程式人生 > >幹貨分享微服務spring-cloud(7.配置中心spring-cloud-config)

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

啟動 style 賬號 分享圖片 地址 config 分布式 efault 沒有

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開啟配置中心功能

技術分享圖片

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

技術分享圖片

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

技術分享圖片

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

技術分享圖片

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配置文件

技術分享圖片

7.2. 客戶端

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

技術分享圖片

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

技術分享圖片

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

技術分享圖片

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

技術分享圖片

關鍵依賴

技術分享圖片

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

技術分享圖片

技術分享圖片

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

技術分享圖片

啟動應用瀏覽器http://localhost:5552/getConfigFromValuehttp://localhost:5552/getConfigFromEnviroment獲取到了github-dev-1.0而並非github-local-1.0技術分享圖片

技術分享圖片

下面 我們來實現動態刷新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

技術分享圖片

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

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

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

技術分享圖片

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