起步
通過官方的腳手架生成工具Spring Initializr 選擇兩個依賴:
- Config Server
- Eureka Discovery Client
配置
開啟ConfigServer
啟動類上增加 @EnableConfigServer 注解(也就是這個注解搭配Auto Configure就算注入了相關(guān)的配置)
application.properties配置文件
# 配置端口、服務(wù)名稱以及本地測試用的存儲目錄
server.port=9000
spring.application.name=config-server
spring.cloud.config.server.git.uri=file:///C:/config
# 因為配置中心本身是無狀態(tài)的,和其他服務(wù)一樣也可以注冊到Registry,也算是一種HA策略吧
eureka.client.region=default
eureka.client.registryFetchIntervalSeconds=5
eureka.client.serviceUrl.defaultZone=http://localhost:9001/eureka/
eureka.instance.prefer-ip-address=true
本地存儲配置的目錄初始化
因為配置中心支持多種底層存儲,常見就是git/svn/jdbc,在C:/config下執(zhí)行g(shù)it init
啟動
main函數(shù)直接run,控制臺打印log一般都是啟動成功以及報錯信息(注冊到eureka報錯,因為還沒啟動注冊中心)
使用
我在哪能看到配置
官方嫡系的配置中心因為底層存儲是可選的,所以沒有一個統(tǒng)一的管理后臺,也就是你用git 就用git相關(guān)的管理工具,jdbc自己做個后臺。
配置中心如何訪問
- /{application}/{profile}[/{label}]
- /{application}-{profile}.yml
- /{label}/{application}-{profile}.yml
- /{application}-{profile}.properties
- /{label}/{application}-{profile}.properties
配置的大概設(shè)計思想
對于某一個服務(wù)來說,一般都會有一個全局配置 + 應用公共配置 + 環(huán)境特有配置,也就是常見的application.properties + application-{profile}.properties
但是由于配置中心是集中式的管理所有應用的配置,當然不可能都叫application,所以采取應用的spring.application.name來區(qū)分不同應用的配置文件,application作為全局配置的默認規(guī)則
拿訂單服務(wù)舉個例子,假如訂單服務(wù)就叫order,那么在SpringCloudConfig里比較典型的一個存儲list:
- application.properties
- order.properties
- order-dev.properties
- order-stg.properties
- order-prd.properties
準備下測試用的配置數(shù)據(jù)
# application.properties
global.xxx=yyy
# order.properties
server.port=10000
order.hello=default
# order-prd.properties
order.hello=prd
這三個文件放到指定的存儲目錄C:/config,并git add commit
測試配置訪問
http://localhost:9000/order/prd
{
"name": "order",
"profiles": ["prd"],
"label": null,
"version": "9a952387b9dd640f9b43a061c2a0d74b1b41de70",
"state": null,
"propertySources": [{
"name": "file:///C:/config/order-prd.properties",
"source": {
"order.hello": "prd"
}
}, {
"name": "file:///C:/config/order.properties",
"source": {
"server.port": "10000",
"order.hello": "default"
}
}, {
"name": "file:///C:/config/application.properties",
"source": {
"global.xxx": "yyy"
}
}]
}
http://localhost:9000/order/default
{
"name": "order",
"profiles": ["default"],
"label": null,
"version": "9a952387b9dd640f9b43a061c2a0d74b1b41de70",
"state": null,
"propertySources": [{
"name": "file:///C:/config/order.properties",
"source": {
"server.port": "10000",
"order.hello": "default"
}
}, {
"name": "file:///C:/config/application.properties",
"source": {
"global.xxx": "yyy"
}
}]
}
default只是一個約定,就算你隨便寫一個不存在的profile也會和default返回結(jié)果一樣(因為沒有order-default.properties)
done!