Spring Cloud入门之消息总线Spring Cloud Bus

Spring Cloud 之 消息总线Spring Cloud Bus

1、Spring Cloud Bus 简介

  Spring Cloud Bus建构在Spring Cloud Stream之上,是一个轻量级的通信组件,可以将分布式系统中的节点与轻量级消息代理连接,从而实现消息或事件的广播。

  Spring Cloud Bus在实现上是基于Spring事件驱动模型(观察者模式的典型应用)进行构建的。Spring事件驱动模型包括以下三个角色:

  • 事件:ApplicationEvent
  • 事件监听者:ApplicationListener
  • 事件发布者:ApplicationEventPublisher

2、 配置自动刷新

  在《Spring Cloud 之 Spring Cloud Config入门》中,我们最后留下了一个关于使用消息总线实现配置信息自动刷新的功能。这里我们通过Spring Cloud Bus 实现配置的刷新。

2.1、配置服务修改

  基于《Spring Cloud 之 Spring Cloud Config入门》中的config-server服务进行改造,首先增加Spring Cloud Bus相关依赖,如下所示:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

 &esmp;然后,修改application.properties配置文件,增肌如下配置:

#actuator相关配置
management.endpoints.web.exposure.include=*

#rabbitmq 配置
spring.rabbitmq.host=192.168.1.9
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin

  其中,management.endpoints.web.exposure.include=*配置需要配置或者只开放bus-refresh端口,不然刷新配置的时候会无效。

  至此,配置服务就修改完成了,是不是很简单呢?这就是Spring Cloud Bus实现轻量级消息广播的能力。

2.2、客户端微服务修改

  客户端修改和服务端类似,也是需要引入spring-cloud-starter-stream-rabbit依赖即可。

2.3、验证自动刷新

  修改完成后,依次启动注册中心、配置服务、和config-clientA、config-clientB两个微服务。然后,访问http://localhost:8091/getStr ,http://localhost:8092/getStr 两个微服务的测试地址,然后修改Git参数对应的test.config配置后,在通过http://localhost:8090/actuator/bus-refresh 刷新配置服务或者任意一个微服务,再访问两个微服务,发现两个微服务的配置同时被刷新了,不用再分别进行刷新了。

2.4、更新部分微服务的配置

  如果我们只想更新部分微服务的配置,可以通过destination参数进行配置,该参数支持格式:“服务名:端口号”这种格式,同时支持“*”通配符,比如我们只想刷新config-clientB这个微服务,我们可以http://localhost:8090/actuator/bus-refresh?destination=config-clientB即可,这个时候,即使config-clientA的配置文件也发生了变化,但是这次刷新不会生效。

猜你喜欢

转载自blog.csdn.net/hou_ge/article/details/111539240