概念
我們使用配置中心時,當配置中心的配置發生了變化,我們就要發送一個post請求給客戶端,讓它重新去拉取新的的配置。當客戶端有很多時,并且還是使用同一份配置文件,這樣當配置中心的配置發生改變,我們就得逐個發送post請求通知,這樣無疑是很浪費人力物力的。
Bus消息總線組件就幫我們解決了這個問題。他的工作流程是這樣的,當配置中心的配置發生了變化時,我們給其中一個客戶端發送post請求,然后client將請求的信息發送到rabbitmq隊列中,然后消息隊列將消息發送給別的隊列。
使用
準備工作
項目基于Spring Cloud 第七章的項目改造。
改造config-client 添加相應坐標
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
<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注解只需要寫在需要刷新配置文件的地方,不一定非要在啟動類中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@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; } } |
配置相關配置
1
2
3
4
5
6
7
8
9
|
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的值。如果是傳統的做法,需要重啟服務,才能達到配置文件的更新。此時,我們只需要發送post請求:http://localhost:8881/actuator/bus-refresh,你會發現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"參數,比如 “/actuator/bus-refresh?destination=customers:**” 即刷新服務名為customers的所有服務。 原理圖
當git文件更改的時候,通過pc端用post 向端口為8882的config-client發送請求/bus/refresh/;此時8882端口會發送一個消息,由消息總線向其他服務傳遞,從而使整個微服務集群都達到更新配置文件。
原文鏈接:https://blog.csdn.net/qq_44333590/article/details/121006985