解析Spring Cloud Bus消息總線
概念
我們使用配置中心時,當配置中心的配置發(fā)生了變化,我們就要發(fā)送一個post請求給客戶端,讓它重新去拉取新的的配置。當客戶端有很多時,并且還是使用同一份配置文件,這樣當配置中心的配置發(fā)生改變,我們就得逐個發(fā)送post請求通知,這樣無疑是很浪費人力物力的。
Bus消息總線組件就幫我們解決了這個問題。他的工作流程是這樣的,當配置中心的配置發(fā)生了變化時,我們給其中一個客戶端發(fā)送post請求,然后client將請求的信息發(fā)送到rabbitmq隊列中,然后消息隊列將消息發(fā)送給別的隊列。
使用
準備工作
項目基于Spring Cloud 第七章的項目改造。
改造config-client 添加相應坐標
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <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>
在啟動類中添加@RefreshScope注解
@RefreshScope注解只需要寫在需要刷新配置文件的地方,不一定非要在啟動類中
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@RestController
@RefreshScope
public class ConfigClientApplication {
/**
* http://localhost:8881/actuator/bus-refresh
*/
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
@Value("${foo}")
String foo;
@RequestMapping(value = "/hi")
public String hi(){
return foo;
}
}
配置相關配置
spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest spring.cloud.bus.enabled=true spring.cloud.bus.trace.enabled=true management.endpoints.web.exposure.include=bus-refresh management.security.enabled=false //報錯加上
- 依次啟動eureka-server、confg-cserver,啟動兩個config-client,端口為:8881、8882。
- 訪問http://localhost:8881/hi 或者http://localhost:8882/hi 瀏覽器顯示:
foo version 3
- 這時我們去代碼倉庫將foo的值改為“foo version 4”,即改變配置文件foo的值。如果是傳統(tǒng)的做法,需要重啟服務,才能達到配置文件的更新。此時,我們只需要發(fā)送post請求:http://localhost:8881/actuator/bus-refresh,你會發(fā)現(xiàn)config-client會重新讀取配置文件
- 1.5版本的post請求http://localhost:8881/bus/refresh
- 2.0版本的post請求http://localhost:8881/actuator/bus-refresh
- 這時我們再訪問http://localhost:8881/hi 或者http://localhost:8882/hi 瀏覽器顯示:
foo version 4
另外,/actuator/bus-refresh接口可以指定服務,即使用"destination"參數(shù),比如 “/actuator/bus-refresh?destination=customers:**” 即刷新服務名為customers的所有服務。 原理圖

當git文件更改的時候,通過pc端用post 向端口為8882的config-client發(fā)送請求/bus/refresh/;此時8882端口會發(fā)送一個消息,由消息總線向其他服務傳遞,從而使整個微服務集群都達到更新配置文件。
相關文章
WebSocket實現(xiàn)數(shù)據(jù)庫更新時前端頁面刷新
這篇文章主要為大家詳細介紹了WebSocket實現(xiàn)數(shù)據(jù)庫更新時前端頁面刷新,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-04-04
淺析Spring容器原始Bean是如何創(chuàng)建的
這篇文章主要是想和小伙伴們一起聊聊?Spring?容器創(chuàng)建?Bean?最最核心的?createBeanInstance?方法,文中的示例代碼講解詳細,需要的可以參考一下2023-08-08
Spring源碼解析之循環(huán)依賴的實現(xiàn)流程
這篇文章主要介紹了Spring源碼解析之循環(huán)依賴的實現(xiàn)流程,文章基于Java的相關內容展開循環(huán)依賴的實現(xiàn)流程,需要的小伙伴可以參考一下2022-07-07

