动态刷新全局广播
设计思想:
- 利用消息总线触发一个客户端/bus/refresh,而刷新所有客户端的配置
- 利用消息总线触发一个服务端ConfigServer的/bus/refresh端点,而刷新所有客户端的配置
方式二更加合适,方式一不合适的原因如下:
- 打破了微服务的职责单一性,因为微服务本身是业务模块,它本不该承担配置刷新的职责。
- 破坏了微服务各个节点的对等性。
- 有一定的局限性。例如,微服务在迁移时,它的网络地址常常会发生变化,此时如果想要做到自动刷新,那就会增加更多的修改。
给cloud-config-center-3344配置中心服务端添加消息总线支持:
<!--添加消息总线RabbitMQ支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
配置:
server:
port: 3344
spring:
application:
name: cloud-config-center #注册进eureka的微服务名
cloud:
config:
server:
git:
uri: https://github.com/ActonZhang1024/springcloud-config.git
search-paths:
- springcloud-config #指定搜索目录
label: master #读取分支
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
#rabbitmq相关配置 15672是web管理界面端口, 5672是MQ访问端口
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
#暴露bus刷新配置的端点
management:
endpoints:
web:
exposure:
include: 'bus-refresh'
给cloud-config-client3355和3366添加消息总线支持:
<!--添加消息总线RabbitMQ支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
配置:bootstrap.yml
server:
port: 3366
spring:
application:
name: config-client
cloud:
config: #Config客户端配置
label: master #分支名称
name: config #配置文件名称
profile: dev #读取后缀
uri: http://localhost:3344 #配置中心地址
#rabbitmq相关配置 15672是web管理界面端口, 5672是MQ访问端口
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
#暴露监控端点
management:
endpoints:
web:
exposure:
include: "*"
测试:
启动eureka,3344配置中心,3355和3366客户端.
访问:localhost:3355/configInfo
和localhost:3366/configInfo
:
修改配置文件config-dev.yml的version=5,并提交到仓库。
访问总线3344:localhost:3344/config-dev.yml
,获取成功
访问3355客户端:localhost:3355/configInfo
,失败,并未刷新
访问3366客户端:localhost:3366/configInfo
,失败,并未刷新
此时,向3344配置中心发送POST请求刷新
此时,配置中心会通过BUS总线通知3355和3366客户端:
动态刷新的定点通知
公式如下:
http://localhost:配置中心端口/actuator/bus-refresh/{destination}
destination就是:微服务名:端口号
/bus/refresh请求不再发送到具体的服务实例上,而是发给config server并通过destination参数类指定需要更新配置的服务或实例。
示例:只通知3355,不通知3366。
修改配置文件config-dev.yml的version=6,并提交到仓库。
发送POST请求刷新:
访问3355:
访问3366:
定点刷新成功!