概述
- 上一节解决了不用重启微服务客户端,就可以获得配置信息,但是还是需要发送post请求刷新才行
- 这一节完成分布式的自动刷新功能
- Spring Cloud Bus配合Spring Cloud Config使用可以实现配置的动态刷新
是什么
- Bus支持两种消息代理,RabbitMQ和Kafka
什么是总线
- 在微服务架构的系统中,通常会使用轻量级的消息代理来构建一个共用的消息主题,并让系统中所有微服务实例都连接上来,由于该主题中产生的消息会被所有实例监听和消费,所以称它为消息总线。在总线上的各个实例,都可以方便地广播一些需要让其他连接在该主题上的实例都知道的消息。
基本原理
- ConfigClient实例都监听MQ中同一个topic(默认是springCloudBus)。当一个服务刷新数据的时候,它会把这个信息放到Topic中,这样其他监听同一Topic的服务就能得到通知,然后去更新自身配置。
安装RabbitMQ
- docker装还是很快的
SpringCloud Bus动态刷新全局广播
- 为了演示效果,按照3355的方式建造一个3366
设计思想
大概有两种思路如下:
- 利用消息总线触发一个客户端/bus/refesh,而刷新所有客户端的配置
- 利用消息总线触发一个服务端ConfigServer的/bus/refesh端点,而刷新所有客户端的配置
第二种的架构显然更加适合,图一不适合
- 打破了微服务的职责单一性,因为微服务本身是业务模块,它本不应该承担配置刷新的职责
- 打破了微服务各节点的对等性
- 有一定的局限性.例如,微服务在迁移时,它的网络地址常常会发生变化,此时如果想要做自动刷新,那就会增加更多的修改
给cloud-config-center-3344配置中心服务端添加消息总线支持
- 增加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
- 修改yml,增加消息队列配置
server:
port: 3344
spring:
application:
name: cloud-config-center
cloud:
config:
server:
git:
uri: https://gitee.com/dogggg/SpringCloud-Config.git
search-paths: #目录
- SpringCloud-Config配置中心
force-pull: true
username: 13526527916
password: xiaoerbi77...
label: master
rabbitmq:
host: 192.168.79.128
port: 5672
username: admin
password: admin
virtual-host: my_vhost
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
#rabbitmq相关配置,暴露bus刷新配置的端点
management:
endpoints:
web:
exposure:
include: 'bus-refresh'
给cloud-config-center-3355客户端添加消息总线支持
- pom
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
- yml
server:
port: 3355
spring:
application:
name: config-client
cloud:
config:
label: master #分支
name: config #配置文件
profile: dev #后缀 就是/master/config-dev.yml
uri: http://localhost:3344
rabbitmq:
host: 192.168.79.128
port: 5672
username: admin
password: admin
virtual-host: my_vhost
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
management:
endpoints:
web:
exposure:
include: "*"
给cloud-config-center-3366客户端添加消息总线支持
- 同上
rabbitmq连不上的时候注意下图红框两处,一个要允许,一个在yml中virtual host要配置正确。
修改远程配置文件内容
刷新配置服务中心
访问客户端发现也更新了
- 消息队列发现SpringCloud创建的队列
SpringCloud Bus动态刷新定点通知
- 人话就是指定具体某一个实例生效而不是全部
- 公式:http://localhost:配置中心的端口号/actuator/bus-refresh/{destination}
- 发给config server并通过destination参数类指定需要更新配置的服务或实例
举个例子,只通知3355
-
curl -X POST “http://localhost:3344/actuator/bus-refresh/config-client:3355”
-
config-client是服务名
-
3355是端口号