分客戶端、服務端。
服務端也稱分布式配置中心,是一個獨立的微服務應用,用來連接配置服務器並為客戶端提供獲取配置信息,加密/解密信息等訪問接口。
客戶端則是通過指定配置中心來管理應用資源,以及與業務相關的配置內容,並在啟動的時候從配置中心獲取和加載配置信息。默認采用 git,並且可以通過 git 客戶端工具來方便管理和訪問配置內容。
<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 標記為服務配置中心
@SpringBootApplication @EnableConfigServer public class ConfigserviceApplication { public static void main(String[] args) { SpringApplication.run(ConfigserviceApplication.class, args); } }
修改配置文件
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.cloud.config.server.git.url 指向githu配置倉庫地址
spring.cloud.config.servier.git.searchpaths 設置搜索配置文件目錄,可以同時指定多個固定路徑,或者/**等匹配符
spring.cloud.config.label 配置倉庫的分支
spring.cloud.config.servier.git.username 配置git訪問的用戶名 (如果配置倉庫是公開項目,就不需要配置)
spring.cloud.config.servier.git.password 配置git訪問的密碼(如果配置倉庫是公開項目,就不需要配置)
新建兩個配置文件,內容如下
testconfgi = version 1.1.1 democonfigclient.message=hello spring io
testconfgi = version 2.2.2 democonfigclient.message=hello spring io
請求資源文件格式如下:
- /{application}/{profile}[/{label}]
- /{application}-{profile}.yml
- /{label}/{application}-{profile}.yml
- /{application}-{profile}.properties
- /{label}/{application}-{profile}.properties
根據規則,定義配置文件,將配置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 的值即可
