一、简介
bus支持两种消息代理:rabbitmq和kafka
spring cloud bus配合springcloud config使用可以实现配置的动态刷新
springcloud bus是用来将分布式系统的节点与轻量级消息系统连接起来的框架,它整合了java的事件处理机制和消息中间件的功能,springcloudbus目前支持rabbitmq和kafka
springcloud bus能管理和传播分布式系统间的消息,就像一个分布式执行器,可用于广播状态更改,事件推送等,也可以当作微服务间的通信通道
1、什么是总线
在微服务框架的系统中,通常会使用轻量级的消息代理来构建一个共用的消息主题,并让系统中所有微服务实例都连接上来,由于该主题中产生的消息会被所有实例监听和消费,所以称它位消息总线,再总线的各个实例,都可以方便的广播一些需要让其他连接再该主题上的实例都知道的消息
2、基本原理
configclient实例都监听mq中同一个topic(默认是springcloudbus)当一个服务刷新数据的时候,他会把这个信息放入到Topic中,这样其他监听同一个Topic的服务就能得到通知,然后去更新自身的配置
二、springcloudbus动态刷新全局广播
-
必须先具备良好的RabbitMQ环境先
-
演示广播效果,增加复杂度,再以3355为模板再制作一个3366
-
设计思想
- 利用消息总线触发一个客户端/bus/refresh,而刷新所有客户端的配置
- 利用消息总线触发一个服务端ConfigServer的/bus/refresh端点,而刷新所有客户端配置
-
图2的架构显然更加合适,图1不合适的原因如下:
-
打破了微服务的职责单一性,因为微服务本身十业务模块,他本不应该承担配置刷新的职责
-
破坏了微服务各节点的对等性
-
有一定的局限性。例如,微服务再迁移时,它的网络地址常常会发生变化,此时如果想要做到自动刷新,那就会增加更多的修改
-
-
给cloud-config-center-3344配置中心服务端添加消息总线支持
-
pom文件修改
<!--添加消息总线mq支持--> <dependency> <groupId>org.springframework.cloud</groupId> <articactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <!--相关暴漏的操作一定要有监控操作--> <dependency> <groupId>org.springframework.boot</groupId> <articactId>spring-boot-starter-actuator</artifactId> </dependency>
-
yml配置添加rabbitmq的支持
server: port:3344 spring: application: name: cloud-config-center #注册进eureka服务器的微服务名 cloud: config: server: git: uri: git@github.com:zzyybs/springcloud-config.git ###搜索目录 search-paths: - springcloud-config label: master ##rabbitmq相关配置 rabbitmq: host: localhost port: 5672 username: guest password: guest #服务注册到eureka地址 eureka: client: service-url: defaultZone: http://localhost:7001/eureka ##rabbitmq相关配置,暴漏bus刷新配置的端点 management: endpoints: #暴漏bus刷新配置的端点 web: exposure: include: 'bus-refresh'
-
-
给cloud-config-center-3355客户端、cloud-config-center-3366客户端添加消息总线支持
-
pom文件修改
<!--添加消息总线mq支持--> <dependency> <groupId>org.springframework.cloud</groupId> <articactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <!--相关暴漏的操作一定要有监控操作--> <dependency> <groupId>org.springframework.boot</groupId> <articactId>spring-boot-starter-actuator</artifactId> </dependency>
-
yml文件修改
#rabbitmq相关配置 15672是web管理界面的端口,5672是mq访问的端口 rabbitmq: host: localhost port: 5672 username: guest password: guest #暴漏监控端点 management: endpoints: web: exposure: include: "*"
-
再业务类上controller添加@RefreshScope, 发现3355获取配置配置没有生效
-
-
测试
-
修改github上配置文件增加版本号
-
发送post请求 curl -X post “http://localhost:3344/actuator/bus-refresh” 一次发送处处生效
-
测试http://config-3344.com:3344/config-dev.yml
http://localhost:3355/configInfo
http://localhost:3366/configInfo
-
-
一次修改,广播通知,处处生效
三、springcloudbus动态刷新定点通知
-
不想全部通知,只想顶点通知 只通知3355 不通知3366
-
简单一句话
指定具体某一个实例生效而不是全部,
公式:http://localhost:3344/actuator/bus-refresh/{destination}/bus/refresh请求不在发送到具体的服务实例上,而是发给config server通过destination参数类指定需要更新配置的服务或者实例
-
案例
我们这里刷新运行再3355端口上的config-client
curl -X POST “http://localhost:3344/actuator/bus-refresh/config-client:3355”
-
通知总结