首页 > 应用开发 > > 微服务SpringCloud之配置中心和消息总线
在 微服务SpringCloud之Spring Cloud Config配置中心SVN 博客中每个client刷新配置信息时需要post请求/actuator/refresh,但客户端越来越多时,,需要每个客户端都执行一遍,这种方案就不太适合了。使用Spring Cloud Bus可以完美解决这一问题。
一、Spring Cloud Bus
Spring cloud bus通过轻量消息代理连接各个分布的节点。这会用在广播状态的变化(例如配置变化)或者其他的消息指令。Spring bus的一个核心思想是通过分布式的启动器对spring boot应用进行扩展,也可以用来建立一个多个应用之间的通信频道。目前唯一实现的方式是用AMQP消息代理作为通道,同样特性的设置(有些取决于通道的设置)在更多通道的文档中。
Spring cloud bus被国内很多都翻译为消息总线,也挺形象的。大家可以将它理解为管理和传播所有分布式项目中的消息既可,其实本质是利用了MQ的广播机制在分布式的系统中传播消息,目前常用的有Kafka和RabbitMQ。利用bus的机制可以做很多的事情,其中配置中心客户端刷新就是典型的应用场景之一,我们用一张图来描述bus在配置中心使用的机制。
二、启动RabbitMq
三、SpringCloud Config Server端
1.引入依赖
Demo是在上篇博客的基础上进行修改,主要增加引入spring-cloud-starter-bus-amqp。
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
View Code
2.新增RabbitMq配置信息
这里主要增加开启消息跟踪、配置rabbitmq相关信息。
spring.cloud.bus.trace.enabled=true
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
management.endpoints.web.exposure.include=*
四、SpringCloud Config Client端
1.引入依赖
Client端和服务端有类似的配置,也是引入spring-cloud-starter-bus-amqp,增加rabbitmq相关配置。
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
View Code
2.新增RabbitMq配置信息
management.endpoints.web.exposure.include=*
## 开启消息跟踪
spring.cloud.bus.trace.enabled=true
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
五、测试
1.依次启动EurekaServer、SpringCloudConfigServer、SpringCloudConfigClient,输入 http://localhost:8001/neo-config/dev 、 http://localhost:8003/hello 。
2.修改配置信息
修改github上的配置信息,再次输入上面的url,在8003端口的是没有更新的,此时需要post请求http://localhost:8001/actuator/bus-refresh来刷新SpringCloudConfigServer。这里在post请求时可能会出现405、404的错误,需要设置management.endpoints.web.exposure.include=*,并且由于springcloud的版本不同,post请求的url也不同。
post请求之后返回204,然后刷新即可看到最新的配置信息。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2752/viewspace-3134354/ ,如需转载,请注明出处,否则将追究法律责任。