SpringCloud教程八:Bus(消息总线)

一、概述

ConfigClient(微服务)从ConfigServer端获取自己对应的配置文件,但是目前的问题是:当远程git仓库配置文件发生改变时,每次都是需要重启ConfigCient(微服务),如果有上百上千个微服务呢?我想我们不会一个个去重启每个微服务,也就是说如何让ConfigServer端通知到ConfigClient端?即ConfigClient端如何感知到配置发生更新?

SpringCloud Bus会向外提供一个http接口,即下图中的/bus/refresh。我们将这个接口配置到git的webhook上,当git上的内容发生改变时,就会自动调用/bus/refresh接口。Bus就会通知ConfigServer,configserver会发布更新消息到消息总线的消息队列,其他服务订阅到该消息就会信息刷新,从而实现整个微服务进行自动刷新。

二、原理

①提交配置出发post请求调用客户端A的/bus/refresh接口

②客户端A收到请求从Server端更新配置并且发送给Spring Cloud Bus消息总线

③Spring Cloud Bus接收消息并通知给其他连线在总线上的客户端,所有总线上的客户端均能接收到消息。

④其他客户端接收到消息,请求Server端获取最新配置

⑤全部客户端均获取到最新的配置

三、实践

继续使用上一遍代码,新增eureka-server module(同教程一),config-client和config-server添加spring-cloud-starter-bus-amqp依赖,

消息中间件使用Rabbitmq,安装方法见https://www.cnblogs.com/51ma/p/12889931.html

config-client:

在配置文件bootstarp.properties中加上RabbitMq的配置,包括RabbitMq的地址、端口,用户名、密码,代码如下:

spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
# spring.rabbitmq.username=
# spring.rabbitmq.password=

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

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

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

1 foo version 25

这时我们去git将foo的值改为“foo version 26”,即改变配置文件foo的值。如果是传统的做法,需要重启服务,才能达到配置文件的更新。此时,我们只需要发送post请求(postman即可):http://localhost:8881/bus/refresh,你会发现config-client会重新读取配置文件

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

1 foo version 26

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

四、参考资料

spring_cloud_bus

五、源码

加入qq群:Spring全家桶技术交流①群196165973,免费获取源码。

原文地址:https://www.cnblogs.com/51ma/p/12895415.html