消息总线(Spring Cloud Bus)

Spring Cloud Bus讲分布式的节点用轻量级的消息代理连接起来。它可以用户广播配置文件的更改或者服务之间的通讯,也可以用户监控。本文要讲述的是用Spring Cloud Bus实现通知微服务架构的配置文件的更改。

、准备工作

本文还是基于上一篇文章来实现。按照官方文档,我们只需要在配置文件中配置spring-cloud-starter-bus-amqp;这就是说我们需要装rabbitMq。

二、改造config-client

在pom文件加上起步依赖spring-cloud-starter-bus-amqp,

在配置文件application.properties中加上RabbitMq的配置,包括RbbitMq地址、端口、用户名、

密码,

spring.rabbitmq.host=localhost

spring.rabbitmq.port=5672

#spring.rabbitmq.username=

#spring.rabbitmq.password=

如果rabbitmq有用户名密码,输入即可

依次启动eureka-server、config-server 启动两个config-client,端口为:8881、8882

访问http://localhost:8881/hi 或者http://localhost:8882/hi 浏览器显示:

foo version 3

这是我们去代码仓库讲foo的值改为"foo version4",即改变配置文件foo的值。如果是传统的做法,需要重启服务,才能达到配置文件的更新。此时,我们只需要发送post请求:http://localhost/bus/refresh,你会发现config-client会重新读取配置文件

这时我们再访问http://localhost:8881/hi 或者http://localhost:8882/hi 浏览器显示:

foo version 4

另外,/bus/refresh接口可以指定服务,即使用”destination”参数,比如 “/bus/refresh?destination=customers:**” 即刷新服务名为customers的所有服务,不管ip。

三、分析

此时的架构图: 

消息总线(Spring Cloud Bus)_第1张图片

当git文件更改的时候,通过pc端用post 向端口为8882的config-client发送请求/bus/refresh/;此时8882端口会发送一个消息,由消息总线向其他服务传递,从而使整个微服务集群都达到更新配置文件。

你可能感兴趣的:(消息总线(Spring Cloud Bus))