一、消息總線
在上一篇文章講到了Config的動態刷新,由Config自己只能每次手動執行一次post請求,非常不便利,使用消息總線就可以讓配置文件實現自動刷新。SpringCloud中實現了對消息總線的擴充,也就是SpringCloud Bus。Bus支持兩種消息代理,RabbitMQ和Kafka。
消息總線的原理實際上十分簡單,就像微信公衆號一樣,每次更新後,所有訂閱的用戶都會接收到更新。SpringCloud Bus是用來將分佈式節點與輕量級消息系統連接起來的框架,可以用於廣播狀態更改、時間推送等,也可以當作微服務間的通信通道。
二、動態刷新全局廣播
首先我們再製作一個config-client,新建項目後添加依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
然後編寫配置文件application.yml
server:
port: 3366
spring:
application:
name: config-client
cloud:
# Config客戶端配置
config:
label: master # 分支名稱
name: config # 配置文件名稱
profile: dev # 讀取後綴名稱
uri: http://localhost:3344 # 配置中心地址
# 服務註冊Eureka地址
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
# 暴露監控端點
management:
endpoints:
web:
exposure:
include: "*"
然後再啓動類Application中添加註解@EnableEurekaClient,讓其成爲Eureka Client,之後寫一個Controller
@RestController
@RefreshScope
public class TestController{
@Value("${text}")
String text;
@RequestMapping("/hi")
public String getText(){
return "Message: " + text;
}
}
消息總線更新信息的方式有兩種:第一種是利用消息總線觸發一個客戶端/bus/refresh,而刷新所有客戶端的配置;另一種是觸發服務端的/bus/refresh,從而刷新所有的客戶端配置,顯然第二種方式更好。因爲首先微服務有自身的功能,不應該將其添加額外的刷新配置文件的任務,打破了職責單一性。
上面我們再一次實現了一個Config Client,下面我們來將消息總線添加到Config Server和Config Client中,首先在Config Server中添加SpringCloud Bus的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
然後繼續在Config Server中的配置文件application.yml中添加RabbitMQ的相關配置
# RabbitMQ配置
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
# 暴露Bus刷新配置端點
management:
endpoints:
web:
exposure:
include: 'bus-refresh'
下面我們修改一下Config Client,讓其也使用消息總線,首先添加Bus的依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
之後在client的bootstrap.yml中添加相關配置,需要注意的是rabbitmq的配置一定要在spring下面,這裏和server配置不同
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
這樣即可完成消息總線的配置。在每次更新後,運維工程師只需要進行一次config server的更新,即訪問http://localhost:3344/actuator/bus-refresh即可通過消息總線對所有的客戶端進行更新。
三、動態刷新定點通知
有的時候我們希望通過消息總線不要通知全部的客戶端,只更新一部分客戶端,只需要我們更改輸入的URL爲
http://localhost:配置中心端口號/actuator/bus-refresh/{destination}
/bus/refresh不再發送給某一個實例,而是發送給config server並通過destination參數類指定需要更新配置的服務或實例,例如
http://localhost:3344/actuator/bus-refresh/config-client:3355
這樣只會更新3355端口的config client,不會更新其他客戶端的配置文件
參考資料
歡迎加入交流羣QQ1107710098