? Spring Boot 依賴與配置
Maven 依賴
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
.....
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
</dependencies>
? 使用說明
1、部署 Consul
- 參考文檔:Docker 部署 Consul
2、在 resources
路徑下添加配置文件 bootstrap.properties
,示例如下:
# consul 基本配置
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
# 啟用 consul 配置中心
spring.cloud.consul.config.enabled=true
# 基礎(chǔ)文件夾,默認(rèn)值 config
spring.cloud.consul.config.prefix=config
# 應(yīng)用文件夾,默認(rèn)值 application,consul 會(huì)加載 config/<applicationName> 和 config/<defaultContext> 兩份配置,設(shè)置為相同值,則只加載一份
spring.cloud.consul.config.default-context=testApp
spring.application.name=testApp
# 環(huán)境分隔符,默認(rèn)值 ","
spring.cloud.consul.config.profile-separator=-
# 配置轉(zhuǎn)碼方式,默認(rèn) key-value,其他可選:yaml/files/properties
spring.cloud.consul.config.format=properties
# 配置 key 值,value 對應(yīng)整個(gè)配置文件
spring.cloud.consul.config.data-key=data
# 啟用配置自動(dòng)刷新
spring.cloud.consul.config.watch.enabled=true
# 【疑問】請求 consul api 的延遲,單位:秒
spring.cloud.consul.config.watch.wait-time=1
# 刷新頻率,單位:毫秒
spring.cloud.consul.config.watch.delay=10000
3、在 Consul Key/Value 中添加應(yīng)用配置
配置項(xiàng) spring.cloud.consul.config.prefix
指定了基本文件夾為 config
,需要先創(chuàng)建文件夾 config
:
Tips:新建分兩種類型:文件夾、Key/Value,創(chuàng)建文件夾只需在后面加上 "/" 即可
配置項(xiàng) spring.cloud.consul.config.default-context
和 spring.cloud.consul.config.profile-separator
指定了應(yīng)用名和環(huán)境分隔符,例如應(yīng)用 testApp
有環(huán)境 default
、dev
、prod
,只需在 config
目錄下創(chuàng)建 testApp
、testApp-dev
、testApp-prod
三個(gè)文件夾即可:
配置項(xiàng) spring.cloud.consul.config.format
指定了 Value 的轉(zhuǎn)化方式,依據(jù)個(gè)人喜好,可以配置為 yaml
或 properties
,若選擇這兩種方式,需要配置 spring.cloud.consul.config.data-key
,默認(rèn)為 data
,示例配置:
Tips:如需單獨(dú)配置每個(gè) Key/Value,
spring.cloud.consul.config.format
和spring.cloud.consul.config.data-key
均不用設(shè)置
4、配置刷新
spring.cloud.consul.config.watch.delay
設(shè)置了配置的刷新間隔,在 Consul 修改了配置,會(huì)動(dòng)態(tài)同步到應(yīng)用內(nèi)部。