<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
一樣在啓動項中須要添加註解 @EnableConfigServer 標記爲服務配置中心git
@SpringBootApplication @EnableConfigServer public class ConfigserviceApplication { public static void main(String[] args) { SpringApplication.run(ConfigserviceApplication.class, args); } }
修改配置文件web
spring.cloud.config.server.git.uri=https://XXXX/Text/ spring.cloud.config.server.git.searchPaths=respo spring.cloud.config.label=master spring.application.name=config-server server.port=1006
spring cloud config 服務支持git倉庫url讀取配置spring
spring.cloud.config.server.git.url 指向githu配置倉庫地址bootstrap
spring.cloud.config.servier.git.searchpaths 設置搜索配置文件目錄,能夠同時指定多個固定路徑,或者/**等匹配符服務器
spring.cloud.config.label 配置倉庫的分支app
spring.cloud.config.servier.git.username 配置git訪問的用戶名 (若是配置倉庫是公開項目,就不須要配置)運維
spring.cloud.config.servier.git.password 配置git訪問的密碼(若是配置倉庫是公開項目,就不須要配置)分佈式
新建兩個配置文件,內容以下spring-boot
testconfgi = version 1.1.1 democonfigclient.message=hello spring io
testconfgi = version 2.2.2 democonfigclient.message=hello spring io
請求資源文件格式以下:微服務
根據規則,定義配置文件,將配置push到遠程的git倉庫中
而後啓動config-service項目,訪問配置資源 http://localhost:1006/config-client-dev.properties 頁面打印dev文件的配置,說明配置讀取成功
democonfigclient.message: hello spring io testconfgi: version 1.1.1
能夠修改路徑http://localhost:1006/config-client-pro.properties 打印pro配置
democonfigclient.message: hello spring io testconfgi: version 2.2.2
測試各個配置文件是否能夠正常使用只須要在http://localhost:1006/配置文件名稱 (包含文件後綴)就能夠查看
confg客戶端
新建一個configclient項目一樣先添加引用,須要注意client這裏添加的是spring-cloud-starter-config包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency>
新建bootstrap.properties配置文件,boostrap 由父 ApplicationContext 加載,比 applicaton 優先加載
spring.application.name=config-client spring.cloud.config.label=master spring.cloud.config.profile=pro spring.cloud.config.uri= http://localhost:1006/ server.port=1007
spring.cloud.config.uri 設置config服務端
spring.cloud.config.profile 設置加載環境
spring.cloud.config.label 設置配置中心的分支
改造一下啓動項將配置打印出來
@Value("${testconfgi}") String testconfgi; @Value("${democonfigclient.message}") String message; @RequestMapping(value = "/hi") public String hi(){ return testconfgi+" "+message; }
客戶端切換配置分支時只須要修改 spring.cloud.config.profile 的值便可