原 史上最简单的SpringCloud教程 | 第八篇: 消息总线(Spring Cloud Bus)(Finchley版本)
轉載請標明出處:
原文首發于:https://www.fangzhipeng.com/springcloud/2018/08/30/sc-f8-bus/
本文出自方志朋的博客
轉載請標明出處:
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=guestspring.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
另外,/actuator/bus-refresh接口可以指定服務,即使用"destination"參數,比如 “/actuator/bus-refresh?destination=customers:**” 即刷新服務名為customers的所有服務。
三、分析
此時的架構圖:
當git文件更改的時候,通過pc端用post 向端口為8882的config-client發送請求/bus/refresh/;此時8882端口會發送一個消息,由消息總線向其他服務傳遞,從而使整個微服務集群都達到更新配置文件。
本文源碼下載:
https://github.com/forezp/SpringCloudLearning/tree/master/sc-f-chapter8
五、參考資料
http://blog.csdn.net/forezp/article/details/70148235
http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html
掃碼關注有驚喜
(轉載本站文章請注明作者和出處 方志朋的博客)
轉載于:https://www.cnblogs.com/forezp/p/9852080.html
總結
以上是生活随笔為你收集整理的原 史上最简单的SpringCloud教程 | 第八篇: 消息总线(Spring Cloud Bus)(Finchley版本)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做输卵管通液大概需要多少钱?
- 下一篇: 人脸识别的一些资源