spring CloudBus 將分佈式的節點和輕量的消息代理鏈接起來。這能夠用於廣播配置文件的更改或者其餘的管理工做。一個關鍵的思想就是,消息總線能夠爲微服務作監控,也能夠做爲應用程序之間相互通信。git
1、準備工做github
本文仍是基於上一篇文章來實現。按照官方文檔,咱們只須要在配置文件中配置 spring-cloud-starter-bus-amqp ;這就是說咱們須要裝rabbitMq,點擊rabbitmq下載。至於怎麼使用 rabbitmq,搜索引擎下。web
2、改造config-clientspring
在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啓動類代碼以下:app
@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,端口爲:888一、8882。分佈式
訪問http://localhost:8881/hi 或者http://localhost:8882/hi 瀏覽器顯示:foo version 3spring-boot
這時咱們去代碼倉庫將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
3、分析
此時的架構圖:
當Git文件更改的時候,經過pc端用post 向端口爲8882的config-client發送請求/bus/refresh/;此時8882端口會發送一個消息,由消息總線向其餘服務傳遞,從而使整個微服務集羣都達到更新配置文件。