消息总线组件SpringCloudBus

SpringCloudBus简介

Spring Cloud Bus 将分布式的节点用轻量的消息代理连接起来。它可以用于广播配置文件的更改或者服务之间的通讯,也可以用于监控。本文要讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改。

简单的说就是你改动了Git上的配置文件,不需要重启微服务就能自动更新配置。

还是我上一篇博客写的微服务架构的工程来改动:hello-spring-cloud

1、配置服务端

(1)修改hello-spring-cloud-config工程 ,引入依赖

  <!--SpringCloud Bus所需要的依赖begin-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>
  <!--end-->

(2)修改application.yml ,添加配置

#        Spring Cloud Bus 配置begin
  rabbitmq:
    host: 192.168.88.136
management:
  endpoint:
    web:
      exposure:
        include: bus‐refresh
#      end

2、配置客户端

hello-spring-cloud-web-admin-feign模块为例,加入消息总线

(1)修改hello-spring-cloud-web-admin-feign工程 ,引入依赖

        <!--SpringCloud Bus所需要的依赖begin-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-bus</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream-binder-rabbit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--end-->

(2)在码云的配置文件中配置RabbitMQ的地址:

  rabbitmq:
    host: 192.168.88.136

(3)启动hello-spring-cloud-eurekahello-spring-cloud-confighello-spring-cloud-web-admin-feign 看是否正常运行
(4)修改码云上的配置文件 ,将数据库连接IP 改为127.0.0.1 ,在本地部署一份数据
库。
(5)postman测试 url: http://localhost:8888/actuator/bus-refresh Method:
post (此处的作用是自动刷新码云的配置)出现如下图所示:
在这里插入图片描述
(6)再次观察输出的数据是否是读取了本地的mysql数据。

3、自定义配置的读取

如果需要读取yml配置中的自定义属性则需要在controller层上加一个注解:@RefreshScope
在这里插入图片描述
添加后再次进行测试。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章