背景
使用Spring Cloud Config Server,
啟動Service時會從配置中心取配置文件,并注入到應用中,如果在Service運行過程中想更新配置,需要使用Spring Cloud Bus配合實現實時更新。
實現原理
需要借助RabbitMQ等消息中間件來實現服務間的通訊
ConfigServer改造
目標:使ConfigServer暴露bus-refresh接口,通過bus通知服務更新配置
1. pom.xml增加以下依賴
1
2
3
4
5
6
7
8
|
< dependency > < groupId >org.springframework.cloud</ groupId > < artifactId >spring-cloud-starter-bus-amqp</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-actuator</ artifactId > </ dependency > |
2. 配置文件中配置暴露接口
1
|
management.endpoints.web.exposure.include=bus-refresh |
Service改造
1. pom.xml增加以下依賴
1
2
3
4
5
6
7
8
|
< dependency > < groupId >org.springframework.cloud</ groupId > < artifactId >spring-cloud-starter-bus-amqp</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-actuator</ artifactId > </ dependency > |
2. 通過@RefreshScope聲明配置刷新時需要重新注入
1
2
3
|
@RefreshScope @Controller public class LblController { |
測試
1. 修改git倉庫上的配置文件
Service配置沒有更新
2. 調用http://localhost:8081/actuator/bus-refresh(POST)
Service配置更新
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注服務器之家的更多內容!
原文鏈接:https://blog.csdn.net/lblblblblzdx/article/details/81516665