Spring Cloud系列(七):消息总线

在上一篇中,当一个配置中心的客户端启动之后,它所引用的值就无法改变了,但是Spring Cloud 提供了一种手段去解决了这个问题——Spring Cloud Bus。

一、Spring Cloud Bus

先贴出官方文档对消息总线的介绍

Spring Cloud Bus links the nodes of a distributed system with a lightweight message broker. This broker can then be used to broadcast state changes (such as configuration changes) or other management instructions. A key idea is that the bus is like a distributed actuator for a Spring Boot application that is scaled out. However, it can also be used as a communication channel between apps.

内容来源于:https://cloud.spring.io/spring-cloud-bus/reference/html/

大概意思就是Spring Cloud Bus通过一个轻量级的消息代理来连接分布式系统的节点,这个代理可以被用作广播状态的改变(如配置变化)或其他消息指令。其核心思想是通过分布式的启动器对Spring Boot应用进行扩展。它还可以用作应用之间的通讯通道。

Spring Cloud Bus依靠消息队列来发送消息,常用是有RabbitMQ和Kafka,这里我们只介绍RabbitMQ的方式。

二、安装RabbitMQ

RabbitMQ依赖ErLang,如果你的机器还没有安装ErLang需要先安装,或者在安装RanbbitMQ时也会先检查本地的ErLang环境,如果没有即会引导你去安装。在windows上这两个都是傻瓜式安装,这里就不再多说,可以自行搜索教程。安装完成后会自己作为服务启动。

三、添加依赖

我们依然使用之前的项目,在config-client中添加bus的依赖

<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>

四、修改配置

在config-server的application.properties中添加以下配置

management.endpoints.web.exposure.include=bus-refresh

在config-client的application.properties中添加以下配置

management.endpoints.web.exposure.include=bus-refresh

在config-client的bootstrap.properties中添加以下配置

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

继续在config-client中的Controller类加上@RefreshScope注解。

五、启动和测试

启动注册中心、config-server和config-client,我们先访问http://localhost:8001/getFoo,这时返回的值是bar;

接着我们把远程仓库的foo值改为barrrrr,然后访问http://localhost:8001/actuator/bus-refresh进行刷新,但是如果直接在浏览器访问会报异常

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

因为actuator的这个端点不支持GET方法,这时我们可以用curl命令发送POST请求

curl http://localhost:8001/actuator/bus-refresh -X POST

这时在服务的控制台会输出这个日志

Received remote refresh request. Keys refreshed [config.client.version, foo]

再次访问http://localhost:8001/getFoo可以看到返回的值变成了barrrrr。

这是一个客户端的情况,我们也可以通过参数destination来刷新指定的服务,如http://localhost:8001/actuator/bus-refresh?destination=service-id:*就是刷新所有应用名为service-id的服务,不论ip和端口。

六、总结

消息总线的使用就介绍到这里。

源码已经上传到github:https://github.com/spareyaya/spring-cloud-demo/tree/master/chapter7

posted @ 2020-04-29 23:02  我是满意吖  阅读(366)  评论(0编辑  收藏  举报