目录
1.介绍
Spring cloud bus通过轻量消息代理连接各个分布的节点。
这会用在广播状态的变化(例如配置变化)或者其他的消息指令。Spring bus的一个核心思想是通过分布式的启动器对spring boot应用进行扩展,也可以用来建立一个多个应用之间的通信频道
根据此图我们可以看出利用Spring Cloud Bus做配置更新的步骤:
- 1、提交代码触发post给客户端A发送/actuator/bus-refresh
- 2、客户端A接收到请求从Server端更新配置并且发送给Spring Cloud Bus
- 3、Spring Cloud bus接到消息并通知给其它客户端
- 4、其它客户端接收到通知,请求Server端获取最新配置
- 5、全部客户端均获取到最新的配置
2.客户端spring-cloud-config-client改造
2.1 添加依赖
在user,goods等需要配置文件的服务上加入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
2.2 修改config种dev的配置文件
加入:
## 开启消息跟踪
management.endpoints.web.exposure.include= bus-refresh
spring.cloud.bus.trace.enabled=true
2.3 测试
启动项目后,消息队列会增加几个服务的队列
请求:post http://localhost:8002/actuator/bus-refresh
请求user服务后,user,goods等服务同时开始重新去git上拉取最新配置。
3.改进版本
在上面的流程中,我们已经到达了利用消息总线触发一个客户端/actuator/bus/refresh
,而刷新所有客户端的配置的目的。但这种方式并不优雅。原因如下:
- 打破了微服务的职责单一性。微服务本身是业务模块,它本不应该承担配置刷新的职责。
- 破坏了微服务各节点的对等性。
- 有一定的局限性。例如,微服务在迁移时,它的网络地址常常会发生变化,此时如果想要做到自动刷新,那就不得不修改WebHook的配置。
3.1 在config服务中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
3.2 修改config配置文件
server:
port: 9000
spring:
application:
name: live_config
#profiles:
#active: native
cloud:
config:
server:
#native:
#search-locations: classpath:properties/
git:
search-paths: SpringBoot-config
uri: https://github.com/471604821/SpringBoot-config.git
default-label: main
rabbitmq:
host: 127.0.0.1
port: 5672
username: guest
password: guest
eureka:
client:
service-url:
defaultZone: http://localhost:8888/eureka
management:
endpoints:
web:
exposure:
include: bus-refresh
3.3 测试
post请求http://localhost:9000/actuator/bus-refresh
直接请求config服务,刷新所有相关服务,拉取git最新配置。