Spring Cloud Bus
Spring cloud bus经过轻量消息代理链接各个分布的节点。这会用在广播状态的变化(例如配置变化)或者其余的消息指令。Spring bus的一个核心思想是经过分布式的启动器对spring boot应用进行扩展,也能够用来创建一个多个应用之间的通讯频道。目前惟一实现的方式是用AMQP消息代理做为通道,一样特性的设置(有些取决于通道的设置)在更多通道的文档中。java
Spring cloud bus被国内不少都翻译为消息总线,也挺形象的。你们能够将它理解为管理和传播全部分布式项目中的消息既可,其实本质是利用了MQ的广播机制在分布式的系统中传播消息,目前经常使用的有Kafka和RabbitMQ。利用bus的机制能够作不少的事情,其中配置中心客户端刷新就是典型的应用场景之一,咱们用一张图来描述bus在配置中心使用的机制。git
根据此图咱们能够看出利用Spring Cloud Bus作配置更新的步骤:github
一、提交代码触发post给客户端A发送bus/refresh
二、客户端A接收到请求从Server端更新配置而且发送给Spring Cloud Bus
三、Spring Cloud bus接到消息并通知给其它客户端
四、其它客户端接收到通知,请求Server端获取最新配置
五、所有客户端均获取到最新的配置
客户端spring-cloud-config-client改造web
一、添加依赖spring
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency>
须要多引入spring-cloud-starter-bus-amqp
包,增长对消息总线的支持安全
## 刷新时,关闭安全验证 management.security.enabled=false ## 开启消息跟踪 spring.cloud.bus.trace.enabled=true spring.rabbitmq.host=192.168.9.89 spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=123456
配置文件须要增长RebbitMq的相关配置,这样客户端代码就改造完成了。网络
三、测试
依次启动spring-cloud-eureka、spring-cloud-config-server、spring-cloud-config-client项目,在启动spring-cloud-config-client项目的时候咱们会发现启动日志会输出这样的一条记录。架构
2017-05-26 17:05:38.568 INFO 21924 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/bus/refresh],methods=[POST]}" onto public void org.springframework.cloud.bus.endpoint.RefreshBusEndpoint.refresh(java.lang.String)
说明客户端已经具有了消息总线通知的能力了,为了更好的模拟消息总线的效果,咱们更改客户端spring-cloud-config-client项目的端口为800三、8004依次启动,这样测试环境就准备好了。启动后eureka后台效果图以下:并发
咱们先分别测试一下服务端和客户端是否正确运行,访问:http://localhost:8001/neo-config/dev,返回信息:
mvc
{ "name": "neo-config", "profiles": [ "dev" ], "label": null, "version": null, "state": null, "propertySources": [ { "name": "https://github.com/ityouknow/spring-cloud-starter/config-repo/neo-config-dev.properties", "source": { "neo.hello": "hello im dev" } } ] }
说明server端都正常读取到了配置信息。
依次访问:http://localhost:8002/hello、http://localhost:8003/hello、http://localhost:8004/hello,返回:hello im dev。说明客户端都已经读取到了server端的内容。
如今咱们更新neo-config-dev.properties 中neo.hello的值为hello im dev update并提交到代码库中,访问:http://localhost:8002/hello 依然返回hello im dev。咱们对端口为8002的客户端发送一个/bus/refresh的post请求。在win下使用下面命令来模拟webhook.
curl -X POST http://localhost:8002/bus/refresh
执行完成后,依次访问:http://localhost:8002/hello、http://localhost:8003/hello、http://localhost:8004/hello,返回:hello im dev update。说明三个客户端均已经拿到了最新配置文件的信息,这样咱们就实现了图一中的示例。
改进版本
在上面的流程中,咱们已经到达了利用消息总线触发一个客户端bus/refresh,而刷新全部客户端的配置的目的。但这种方式并不优雅。缘由以下:
打破了微服务的职责单一性。微服务自己是业务模块,它本不该该承担配置刷新的职责。
破坏了微服务各节点的对等性。
有必定的局限性。例如,微服务在迁移时,它的网络地址经常会发生变化,此时若是想要作到自动刷新,那就不得不修改WebHook的配置。
所以咱们将上面的架构模式稍微改变一下
这时Spring Cloud Bus作配置更新步骤以下:
一、提交代码触发post请求给bus/refresh
二、server端接收到请求并发送给Spring Cloud Bus
三、Spring Cloud bus接到消息并通知给其它客户端
四、其它客户端接收到通知,请求Server端获取最新配置
五、所有客户端均获取到最新的配置
这样的话咱们在server端的代码作一些改动,来支持bus/refresh
总体架构以下:
完整项目的源码来源
愿意了解框架技术或者源码的朋友直接求求交流分享技术: 贰一四七七七五六叁叁