一. 搭建配置中心
-
準備git倉庫:
-
新建springboot應用,創建config-server
-
pom.xml中添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
-
添加application.yml
#服務名稱
spring:
application:
name: config-server
cloud:
config:
server:
git:
uri: https://gitee.com/waitforxy/config_cloud
username: [email protected]
password: xdclass.net123
timeout: 5
default-label: master
#服務的端口號
server:
port: 9100
#指定註冊中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
-
啓動類添加註解
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
-
訪問方式(一定要注意語法,如果有問題,會出錯)
-
類型
-
/{name}-{profiles}.properties
-
/{name}-{profiles}.yml
-
/{name}-{profiles}.json
-
/{label}/{name}-{profiles}.yml
-
-
變量解釋:
-
name 服務器名稱
-
profile 環境名稱,開發、測試、生產
-
lable 倉庫分支、默認master分支
-
-
注意:git放的yml但是後綴更改properties,git會自動轉碼
二. 配置客戶端
-
添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
-
修改對應服務的配置文件,把application.yml 改爲 bootstrap.yml
#指定註冊中心地址
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
#服務的名稱
spring:
application:
name: product-service
#指定從哪個配置中心讀取
cloud:
config:
discovery:
service-id: CONFIG-SERVER
enabled: true
profile: test
#建議用lable去區分環境,默認是lable是master分支
#label: test
-
注意點:
-
配置文件要用bootstrap.yml
-
默認讀取文件名是 服務名稱
-
三. 配置中心動態刷新
-
在config-clinet的pom.xml中新增spring-boot-starter-actuator監控模塊,其中包含了/refresh刷新API。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
-
通過上面的介紹,大家不難想到,該功能還可以同Git倉庫的Web Hook功能進行關聯,當有Git提交變化時,就給對應的配置主機發送/refresh請求來實現配置信息的實時更新。但是,當我們的系統發展壯大之後,維護這樣的刷新清單也將成爲一個非常大的負擔,而且很容易犯錯,那麼有什麼辦法可以解決這個複雜度呢?後續我們將繼續介紹如何通過Spring Cloud Bus來實現以消息總線的方式進行通知配置信息的變化,完成集羣上的自動化更新。