前言
上篇文章讲了Spring Cloud Config组件结合Eureka的案例,通过config server工程可以统一管理远程Git仓库的信息,并结合eureka组件来进行服务注册,这样其他的服务就可以进行调用从而获取远程的配置信息,同时也实现了config server工程的高可用。
通过这样的方式来管理配置信息固然方便,但仍有些许业务上的缺陷,那就是如果更改了远程仓库的配置信息,config server工程就需要重启,在高可用的情况下,将出现启动多个工程的情况,这无疑会耗费大量的人力和时间,而Spring Cloud Bus 便可以完美解决这个问题。
Spring Cloud Bus介绍
Spring cloud bus通过轻量消息代理连接各个分布的节点,可以用于广播状态的变化或者其他的消息,例如配置信息的变化。其本质是利用MQ的广播机制在分布式系统中传播消息,目前springcloud 中支持的MQ组件有Kafka和RabbitMQ 。本文将讲述如何用 Spring Cloud Bus 集合RabbitMQ 来实现刷新更改微服务中的配置信息。
当远程Git 仓库的配置更改后,只需要向某一个微服务实例发送一个Post 请求 “/bus/refresh ”,通过消息组件通知其他微服务实例重新拉取配置文件。架构图如下:
准备工作
本文的项目用到的消息中间件是RabbitMq,所以读者们若要自己实现案例效果,需在电脑上安装好RabbitMq,安装过程不在此赘述,请大家自己上网查询。
项目实例
因为本文展示的是结合Spring Cloud Bus 更新获取配置的例子,所以需要用到上一章文章的工程,先改造config-client工程,在pom文件加上起步依赖spring-cloud-starter-bus-amqp:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
接着是修改配置文件,需要在原有的基础加上RabbitMq的相关信息,以及spring.cloud.bus的配置,具体如下:
spring:
application:
name: config-client
cloud:
config:
label: master
profile: dev
uri: http://localhost:1113/
discovery:
enabled: true
service-id: config-server
bus:
enabled: true
trace:
enabled: true
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
server:
port: 1114
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8889/eureka/
management:
endpoint:
bus-refresh:
enabled: true
配置信息里新增了rabbitMq的地址,端口,用户名和密码,以及开启 bus-refresh 的验证。依次开启eureka-server,config-server,config-client三个工程,访问http://localhost:8889/,可以看到两个服务成功注册。
访问地址http://localhost:1114/user ,可以看到浏览器成功输出
yeya
这是git仓库里配置文件对应的值,我们到仓库里把值改为 yeya11111111
再次访问http://localhost:1114/user ,发现输出仍是 “yeya” ,这是因为配置信息改变了,服务没有重启的话是读取不到实时的配置信息的,我们用postman模拟发出一个post请求http://localhost:8889/bus/refresh ,通知微服务消息更新:
在浏览器再次访问 http://localhost:1114/user ,可以看到浏览器成功输出
yeya11111111
说明微服务的消息通知成功了。
其他
Spring Cloud Bus可以实现局部刷新的功能,某些场景下,我们可能只想刷新部分微服务的配置,此时可通过/bus/refresh
端点的destination参数来定位要刷新的应用程序。
例如:/bus/refresh?destination=customers:8000
,这样消息总线上的微服务实例就会根据destination参数的值来判断是否需要要刷新。其中,customers:8000
指的是各个微服务的ApplicationContext ID。
destination参数也可以用来定位特定的微服务。例如:/bus/refresh?destination=customers:**
,这样就可以触发customers微服务所有实例的配置刷新。
源码地址:https://github.com/Taoxj/SpringCloudDemo/tree/master/busDemo