此文章僅寫給自己及同事探討使用,不可作為教程學(xué)習(xí)
為什么需要分布式配置中心:
分布式系統(tǒng)中,服務(wù)數(shù)量太多,為了方便服務(wù)配置文件的統(tǒng)一管理,所以我們需要分布式配置中心組件。
在沒有使用配置中心時:
1,配置文件分散在各個項目里,不方便維護
2,配置文件的權(quán)限與安全得不到保障
3,配置文件更新,項目需要重啟
POM:
添加依賴:<dependency>
? ? ? ? ? ????? ????<groupId>org.springframework.cloud</groupId>
? ? ? ? ? ? ????????<artifactId>spring-cloud-starter-config</artifactId>
? ? ? ? ?????????</dependency>
模塊配置文件:(bootstrap.yml)
spring:
application:
#應(yīng)用名,需要保持與服務(wù)器中需要讀取的配置名一致,如服務(wù)器中此配置文件名為test-config-#dev.properties,去除dev(表示環(huán)境為dev)及后綴
name: test-config
cloud:
config:
uri: http://localhost:9001/????#config server的uri
? ? ? profile: dev????#指定環(huán)境
? ? ? label: master????#指定分支
server:
port:9201
配置文件手動刷新:
/refresh:
添加spring-boot-starter-actuator依賴,
在Controller上添加注解@RefreshScope
發(fā)送post請求請求localhost:8081/refresh
再重新訪問即可(此方法了解即可)
實現(xiàn)配置文件的動態(tài)刷新:(config+bus)
spring-cloud-bus:消息總線,利用消息隊列的方式實現(xiàn)動態(tài)的刷新,配置文件客戶端(需要獲取配置文件的微服務(wù)端)訂閱此消息隊列(配置更新事件),當(dāng)其中一個微服務(wù)節(jié)點的/bus/refresh端點被請求時,該實例就會向消息總線發(fā)送一個配置更新事件,其他實例獲得該事件后也會更新配置。
添加依賴:
<dependency>
????<groupId>org.springframework.boot</groupId>
????<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
????<groupId>org.springframework.cloud</groupId>
????<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
在Controller上添加注解@RefreshScope
安裝rabbitmq
client模塊中配置文件(bootstrap.yml)中添加
spring:
rabbitmq:
host:? ? ? ? ? ? ? ? ? ? ?#rabbitmq所在主機ip地址
port:? ? ? ? ? ? ? ? ? ? ? #rabbitmq端口
username:? ? ? ? ? ? guest
password:? ? ? ? ? ? guest
management:
endpoints:
web:
exposure:
include:bus-refresh
啟動配置中心服務(wù)端與客戶端(可以啟動多個不同端口的客戶端便于測試)
更改git服務(wù)器上的配置文件,此時直接通過服務(wù)端訪問可以得到修改后的內(nèi)容,但客戶端不會跟著刷新。
發(fā)送post請求(可以使用postman或者終端)
訪問http://localhost:9201(其中一個客戶端的ip)/actuator/bus-refresh
再次通過客戶端訪問(http://localhost:9201/value)可以得到修改后的配置文件內(nèi)容
此時其他客戶端,例如(http://localhost:9202/value)也會一起進行更新