原 史上最簡單的SpringCloud教程 | 第八篇: 訊息匯流排(Spring Cloud Bus)(Finchley版本)
轉載請標明出處:
Spring Cloud Bus 將分散式的節點用輕量的訊息代理連線起來。它可以用於廣播配置檔案的更改或者服務之間的通訊,也可以用於監控。本文要講述的是用Spring Cloud Bus實現通知微服務架構的配置檔案的更改。
一、準備工作
本文還是基於上一篇文章來實現。按照官方文件,我們只需要在配置檔案中配置 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
重新讀取配置檔案:
這時我們再訪問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埠會發送一個訊息,由訊息匯流排向其他服務傳遞,從而使整個微服務叢集都達到更新配置檔案。
本文原始碼下載:
五、參考資料
掃碼關注有驚喜
(轉載本站文章請註明作者和出處 方誌朋的部落格)