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

前言

讀者:對spring、spring boot有必定了解git

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

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

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


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對配置中心支持springboot

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,app

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

相關文章
相關標籤/搜索