分析
之前使用actuator监控中心完成刷新功能,但是在Config Client服务端需要发送POST请求来手动刷新,如果Config Client有很多的话,那么需要一个一个地发送POST请求,这显然是不现实的做法。
方案
使用消息队列中的Topic, 通过消息实现通知。
目前Spring Cloud Bus消息总线只是实现了对RabbitMQ以及Kafka的支持。
需要装RabbitMQ
参考《RabbitMQ教程》 https://blog.csdn.net/hellozpc/article/details/81436980
SpringCloudBus的架构


改造config-client
在pom文件加上起步依赖spring-cloud-starter-bus-amqp。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
在bootstrap.yml添加rabbitmq的配置
spring:
application:
name: config-client
cloud:
bus:
enabled: true
trace:
enabled: true
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
#开启所有端点
management:
endpoints:
web:
exposure:
include: "*"
启动测试
保证Rabbit的服务开启。
RabbitMQ后台管理:http://127.0.0.1:15672
帐号密码:guest/guest

启动config-client工程后查看RabbitMQ中的交换机:

查看队列:

查看该队列绑定到了springCloudBus

修改config-client服务的端口,再启动一个config-client实例,进行测试。

发现,有2个队列,分别都绑定到springCloudBus的交换机。
在Git上修改配置文件的内容进行测试。
然后发送post请求:curl -X POST http://localhost:8096/actuator/bus-refresh
会发现所有config-client的配置都更新了。
流程总结
更新文件到git服务器,发送post请求/bus/refresh,实例将消息发送到springCloudBus的交换机,由于这个实例的队列页绑定到交换机,所以其他实例也获取到了更新的通知,然后去Config Server获取最新的数据。
架构优化
在前面实现的架构中,config-client实例应该是一个具体业务相关的服务,但是我们让它负责了发送更新的消息到RabbitMQ。
这其实是违反了微服务架构中的职责单一的原则。
其实这个架构是可以改进的,就是将原有的Config Server不仅仅提供配置查询的服务,而且还要负责更新消息的发送。

改造config-server
导入依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--整合Spring Cloud Bus-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
在application.yml添加rabbitmq的配置。
然后config-server服务上发送actuator/bus-refreshPOST请求就可以将配置更新到所有的config-client服务上。
本文介绍如何使用SpringCloud Bus结合RabbitMQ实现配置自动刷新,避免手动刷新多个ConfigClient服务的繁琐操作。通过消息队列的Topic,实现配置更新通知,优化微服务架构。

492

被折叠的 条评论
为什么被折叠?



