配置服務(wù)器默認(rèn)采用git來存儲(chǔ)配置信息,也可以本地存儲(chǔ)贫途。
配置中心配置
1. pom.xml中加入spring-cloud-config-server,spring-cloud-starter-eureka
2. 主類中配置@EnableConfigServer @EnableEurekaClient
3. application.yml配置
spring.application.name=config-server
server.port=60002
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/
4. 若使用本地存儲(chǔ):
spring.profiles.active=native
spring.cloud.config.server.native.search-locations=classpath:/config
在resource目錄下創(chuàng)建config目錄丢早,里面配置clientA-dev.yml,clientA-test.yml等
5. 若使用git存儲(chǔ):
spring.cloud.config.server.git.uri=http://git.oschina.net/didispace/SpringBoot-Learning/
spring.cloud.config.server.git.searchPaths=Chapter9-1-4/config-repo
spring.cloud.config.server.git.username=username
spring.cloud.config.server.git.password=password
uri:配置git倉庫位置;searchPaths:配置倉庫路徑下的相對(duì)搜索位置怨酝,可以配置多個(gè);username:訪問git倉庫的用戶名赡艰;password:訪問git倉庫的用戶密碼
客戶端A配置
1. pom.xml中加入spring-cloud-starter-eureka,spring-cloud-starter-config
2. spring.application.name=clientA
spring.cloud.config.enabled=true
spring.cloud.config.discovery.enabled=true
spring.cloud.config.discovery.service-id=config-server
spring.cloud.config.profile=dev
spring.cloud.config.label=master
eureka.client.serviceUrl.defaultZone=http://localhost:10001/eureka/
解釋:
配置中心的{application}-{profile}.properties配置文件斤葱,{label}對(duì)應(yīng)git上不同的分支,默認(rèn)為master揍堕。
spring.application.name:對(duì)應(yīng){application}部分
spring.cloud.config.profile:對(duì)應(yīng){profile}部分
spring.cloud.config.label:對(duì)應(yīng)git的分支。如果配置中心使用的是本地存儲(chǔ)惯驼,則該參數(shù)無用
spring.cloud.config.uri:配置中心的具體地址(不建議使用,因?yàn)椴焕谪?fù)載均衡)
spring.cloud.config.discovery.service-id:指定配置中心的service-id祟牲,便于擴(kuò)展為高可用配置集群。
特別注意:上面這些與spring-cloud相關(guān)的屬性必須配置在bootstrap.properties中议惰,config部分內(nèi)容才能被正確加載乡恕。因?yàn)閏onfig的相關(guān)配置會(huì)先于application.properties,而bootstrap.properties的加載也是先于application.properties傲宜。例如上面的defaultZone如果不配置,則找不到service-id辆憔,會(huì)導(dǎo)致啟動(dòng)失敗报嵌。
配置中心集群:
1. config-server主類配置@EnableEurekaClient,并啟動(dòng)多個(gè)锚国,相當(dāng)于有多個(gè)配置中心注冊(cè)在服務(wù)中心;
2. config-client的properties配置中使用spring.cloud.config.discovery.service-id指定config-server血筑,實(shí)現(xiàn)負(fù)載均衡。如此梆砸,任意一個(gè)config-server節(jié)點(diǎn)crash了也不影響config-client的運(yùn)行园欣。
配置實(shí)時(shí)刷新
配置中心的數(shù)據(jù)修改后,客戶端可實(shí)時(shí)獲取更新內(nèi)容沸枯,實(shí)現(xiàn)方式:
1. config-client的pom.xml中新增spring-boot-starter-actuator監(jiān)控模塊,其中包含了/refresh刷新API哪轿。
2. git中配置數(shù)據(jù)修改后翔怎,config-client中執(zhí)行http://localhost:18443/refresh 即可實(shí)現(xiàn)client端配置數(shù)據(jù)更新
實(shí)例源碼: config-server