Spring Cloud Bus 将分布式的節點用輕量的消息代理連接配接起來。它可以用于廣播配置檔案的更改或者服務之間的通訊,也可以用于監控。可使用AMQP(RabbitMQ)或Kafka作為通道。
消息總線(Bus)的典型應用場景就是配置中心用戶端重新整理。
一、用戶端發起通知,架構圖如下:
流程步驟說明:
- webhook監聽被觸發,給configClient A發送bus-refresh請求重新整理配置
- configClient A讀取configServer中的配置,并且發送消息給Bus
- Bus接收消息後并通知其他configClient
- 其他configClient收到消息讀取最新配置
下面将對ConfigClient進行改造(eureka_ribbon):
1. pom.xml引入amqp
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
2. application.properties
#Actuator endpoints
management.endpoints.web.exposure.include=info,health,refresh,bus-refresh
#Tracing Bus Events
spring.cloud.bus.trace.enabled=true
#RabbitMQ
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password=123
3. 測試
1)啟動兩個eureka_ribbon
2)在RabbitMQ的控制台,可以看到多了2個SpringCloudBus的queue
3)分别通路eureka_ribbon的配置
http://127.0.0.1:9201/getHelloName
http://127.0.0.1:9204/getHelloName
4) 修改github上的配置檔案
5) 使用postman以POST的方式調用http://127.0.0.1:9201/actuator/bus-refresh
6)再次分别通路eureka_ribbon的配置
http://127.0.0.1:9201/getHelloName
http://127.0.0.1:9204/getHelloName
7)檢視背景日志可以看到client收到bus的消息
2019-06-20 17:46:06.203 INFO 22048 --- [nio-9201-exec-6] o.s.cloud.bus.event.RefreshListener : Received remote refresh request. Keys refreshed [management.endpoints.web.exposure.include, config.client.version, hello.name]
用戶端發起通知缺陷:
1. 導緻各用戶端節點不對等,以及打破了微服務的職責單一性;
2. 用戶端位址會發生變化(相對頻次高),存在一定局限性;
二、服務端發起通知
為了解決用戶端發起通知缺陷,改用服務端發起通知,架構圖如下:
流程步驟說明:
- webhook監聽被觸發,給configServer發送bus-refresh請求重新整理配置
- configServer發送消息給Bus
- Bus接收消息後并通知所有configClient
- 各configClient收到消息讀取最新配置
從圖上可以看出,configClient用戶端的職責就是接收重新整理消息讀取配置,而且各用戶端完全對等。
下面對ConfigServer進行改造:
1. pom.xml引入amqp
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
2. application.properties
#Actuator endpoints
management.endpoints.web.exposure.include=bus-refresh
#Tracing Bus Events
spring.cloud.bus.trace.enabled=true
#RabbitMQ
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password=123
3. 測試
1)啟動configServer
2)修改github上的配置檔案
3)調用configServer的bus-refresh, http://127.0.0.1:9111/actuator/bus-refresh
4)通路用戶端,均已更新為最新配置
三、局部重新整理
有時候需要針對特定的服務的配置進行重新整理
1. 重新整理單個執行個體
可以通過配置spring.cloud.bus.id來辨別執行個體的service ID,預設使用應用名spring.application.name加端口server.port,如:
http://127.0.0.1:9111/actuator/bus-refresh/eurekaRibbon:9201
重新整理後,9201擷取了最新的配置,但9204還是舊的配置
2. 通配符重新整理執行個體
http://127.0.0.1:9111/actuator/bus-refresh/eurekaRibbon:**
調用後:
參考:
https://cloud.spring.io/spring-cloud-static/Greenwich.SR1/single/spring-cloud.html#_spring_cloud_bus