前言
上篇文章讲了Spring Cloud Config组件结合Eureka的案例,经过config server工程能够统一管理远程Git仓库的信息,并结合eureka组件来进行服务注册,这样其余的服务就能够进行调用从而获取远程的配置信息,同时也实现了config server工程的高可用。git
经过这样的方式来管理配置信息当然方便,但仍有些许业务上的缺陷,那就是若是更改了远程仓库的配置信息,config server工程就须要重启,在高可用的状况下,将出现启动多个工程的状况,这无疑会耗费大量的人力和时间,而Spring Cloud Bus 即可以完美解决这个问题。github
Spring Cloud Bus介绍
Spring cloud bus经过轻量消息代理链接各个分布的节点,能够用于广播状态的变化或者其余的消息,例如配置信息的变化。其本质是利用MQ的广播机制在分布式系统中传播消息,目前springcloud 中支持的MQ组件有Kafka和RabbitMQ 。本文将讲述如何用 Spring Cloud Bus 集合RabbitMQ 来实现刷新更改微服务中的配置信息。
当远程Git 仓库的配置更改后,只须要向某一个微服务实例发送一个Post 请求 “/bus/refresh ”,经过消息组件通知其余微服务实例从新拉取配置文件。架构图以下:
web
准备工做
本文的项目用到的消息中间件是RabbitMq,因此读者们若要本身实现案例效果,需在电脑上安装好RabbitMq,安装过程不在此赘述,请你们本身上网查询。spring
项目实例
由于本文展现的是结合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 ,能够看到浏览器成功输出app
yeya
这是git仓库里配置文件对应的值,咱们到仓库里把值改成 yeya11111111
再次访问http://localhost:1114/user ,发现输出还是 “yeya” ,这是由于配置信息改变了,服务没有重启的话是读取不到实时的配置信息的,咱们用postman模拟发出一个post请求http://localhost:8889/bus/refresh ,通知微服务消息更新:
在浏览器再次访问 http://localhost:1114/user ,能够看到浏览器成功输出分布式
yeya11111111
说明微服务的消息通知成功了。svg
其余
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
本文分享 CSDN - 鄙人薛某。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。