spring CloudBus 將分佈式的節點和輕量的消息代理連接起來。這可以用於廣播配置文件的更改或者其他的管理工作。一個關鍵的思想就是,消息總線可以爲微服務做監控,也可以作爲應用程序之間相互通訊。
一、準備工作
本文還是基於上一篇文章來實現。按照官方文檔,我們只需要在配置文件中配置 spring-cloud-starter-bus-amqp ;這就是說我們需要裝rabbitMq,點擊rabbitmq下載。至於怎麼使用 rabbitmq,搜索引擎下。
二、改造config-client
在pom文件加入spring-cloud-starter-bus-amqp,完整的配置文件如下:
<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>
在配置文件application.properties中加上RabbitMq的配置,包括RabbitMq的地址、端口,用戶名、密碼。並需要加上spring.cloud.bus的三個配置,具體如下:
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
ConfigClientApplication啓動類代碼如下:
@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;
}
}
依次啓動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會重新讀取配置文件
這時我們再訪問http://localhost:8881/hi 或者http://localhost:8882/hi 瀏覽器顯示:foo version 4
另外,/bus/refresh接口可以指定服務,即使用”destination”參數,比如 “/bus/refresh?destination=customers:” 即刷新服務名爲customers的所有服務,不管ip。歡迎大家一起學習研究相關技術願意瞭解源碼的朋友直接求求交流分享技術:2147775633
三、分析
此時的架構圖:
當Git文件更改的時候,通過pc端用post 向端口爲8882的config-client發送請求/bus/refresh/;此時8882端口會發送一個消息,由消息總線向其他服務傳遞,從而使整個微服務集羣都達到更新配置文件。