為什么需要使用配置中心
1、服務(wù)配置的現(xiàn)狀

2、常用的配置管理解決方案的缺點(diǎn)

3、為什么要使用 spring cloud config 配置中心

4、spring cloud config 配置中心,它解決了什么問題

編寫配置中心入門案例
編寫配置中心的服務(wù)端
添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
application配置
#配置服務(wù)名及端口
spring.application.name=config-server
server.port=9020
#設(shè)置服務(wù)注冊中心地址
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
#Git 配置
#倉庫地址
spring.cloud.config.server.git.uri=https://gitee.com/zhao2020/SpringCloudConfig
#spring.cloud.config.server.git.username=賬戶名
#spring.cloud.config.server.git.password=或密碼
啟動類添加@EnableConfigServer注解
@EnableEurekaClient
@EnableConfigServer
@SpringBootApplication
public class ConfigServerlication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerlication.class, args);
}
}
在git中上傳properties配置文件
測試:通過Spring cloud config server可以直接獲取配置文件內(nèi)容

配置文件的命名規(guī)則與訪問

編寫配置中心的客戶端(就是我們的服務(wù))
依賴
<!--config client客戶端的依賴-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!--熱部署的依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application配置
#設(shè)置服務(wù)名稱和端口
spring.application.name=config-client
server.port=9021
#設(shè)置服務(wù)注冊中心地址
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
#默認(rèn) false,這里設(shè)置 true,表示開啟讀取配置中心的配置
spring.cloud.config.discovery.enabled=true
#對應(yīng) eureka 中的配置中心 serviceId,默認(rèn)是 configserver
spring.cloud.config.discovery.serviceId=config-server
#指定環(huán)境
spring.cloud.config.profile=dev
#git 標(biāo)簽
spring.cloud.config.label=master
#springboot 默認(rèn)開啟了權(quán)限攔截 會導(dǎo)致 /refresh 出現(xiàn) 401,拒絕訪問
management.security.enabled=false
編寫一個方法進(jìn)行測試
@RestController
@RefreshScope //熱部署時刷新作用域中的數(shù)據(jù)
public class TestController {
@Value("${e-book}")
String msg;
@RequestMapping("showMsg")
public String showMsg(){
return msg;
}
}
測試,獲取到了遠(yuǎn)程git倉庫中的properties文件中的內(nèi)容
配置中心原理

本地服務(wù)啟動后,默認(rèn)會從本地git倉庫(Spring config server)中獲取配置文件,本地git倉庫會從遠(yuǎn)程git倉庫獲取配置文件,并緩存到本地。當(dāng)本地服務(wù)進(jìn)行重啟(或利用熱部署刷新項(xiàng)目)后,將會重新從遠(yuǎn)程git倉庫獲取配置文件。
利用cURL發(fā)送POST請求進(jìn)行熱部署加載遠(yuǎn)程Git倉庫的配置文件
注意,X和POST一定要是大寫
curl 127.0.0.1:9021/refresh -X POST