SpringCloud系列——Bus 消息總線

  前言

  SpringCloud Bus使用輕量級消息代理將分佈式系統的節點鏈接起來。而後可使用此代理廣播狀態更改(例如配置更改)或其餘管理指令。本文結合RabbitMQ+GitHub的Webhook實現上篇博客Config配置中心(SpringCloud系列——Config 配置中心)的自動刷新html

  官方文檔:https://cloud.spring.io/spring-cloud-static/spring-cloud-bus/2.1.0.RC3/single/spring-cloud-bus.htmlgit

 

  RabbitMQ安裝

  參考:http://www.javashuo.com/article/p-uwaqfhdi-ey.htmlgithub

  大概步驟:web

  一、先去下載Erlang、RabbitMQspring

  二、先安裝Erlang環境、配置ERLANG_HOME環境變量、安裝RabbitMQ緩存

  三、激活RabbitMQ 管理插件,登陸http://localhost:15672,使用默認帳號登陸,用戶名、密碼都是:guestspringboot

  

  代碼編寫

  確保RabbitMQ中間件可用以後咱們開始對上一篇的項目進行調整,我這裏直接使用默認帳號鏈接RabbitMQ,5672是RabbitMQ的監聽端口maven

 

  Config Server

  maven引入bus-amqp分佈式

        <!-- bus-RabbitMQ -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>

  配置文件添加對RabbitMQ的相關配置post

#bus-rabbitMQ
spring.cloud.bus.trace.enabled=true
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

  同時,配置中心擔任調用/bus-refresh的任務

#暴露端點
management.endpoints.web.exposure.include=bus-refresh

  

  Config Client

  客戶端同時也要鏈接到消息總線

  maven引jar

        <!-- bus-RabbitMQ -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>

  配置文件添加

#bus-rabbitMQ
spring.cloud.bus.trace.enabled=true
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

 

  效果演示

  啓動全部項目

  Config Server訪問 http://localhost:1112/myspringboot-dev.properties/

  Config Server訪問 http://localhost:10087/index

  前往GitHub修改 huanzi.qch.config.server.username: 張三2

  修改完以後回去刷新Config Server跟Config Client,server能實時更新獲取最新數據,client不能實時獲取最新數據,讀的是緩存

  Config Server post調用 http://localhost:1112/actuator/bus-refresh

  打印空?不要緊,刷新Config Client的http://localhost:10087/index,已經獲取到了最新數據

 

  WebHook

  GitHub的webhook容許在某些事件發生時通知外部服務。當指定的事件發生時,咱們將向您提供的每一個url發送POST請求。

  登陸GitHub,前往建立一個WebHook

  須要能被外網訪問,因此這裏演示不了...

  這樣,在每次push以後都會觸發webhook事件,從而實現Config配置中心的自動刷新

 

  總結

   更多springcloud bus配置請查閱官方文檔

 

  代碼開源

  代碼已經開源、託管到個人GitHub、碼雲:

  GitHub:https://github.com/huanzi-qch/springCloud

  碼雲:https://gitee.com/huanzi-qch/springCloud

相關文章
相關標籤/搜索