0%

使用消息总线进行动态刷新

使用消息总线进行动态刷新

Spring Cloud Bus是将分布式系统的节点与轻量级消息系统链接起来的框架,整合了java的时间处理机制和消息中间件功能,目前支持RabbitMQ和kafka,构建一个共用的消息主题,并让系统中所有的微服务实例都连接上来,该主题产生的消息会被所有实例监听和消费,所以被称为消息总线

动态刷新配置

ConfigClient实例都监听MQ中同一个topic(默认是springCloudBus),当一个服务刷新数据时,会把这个信息放入到Topic中,这样其他监听同一Topic的服务就能得到通知,然后更新自身的配置

有两种实现方式

第一种

利用消息总线触发一个客户端/bus/refresh,从而刷新所有客户端的配置

第二种

利用消息总线触发Config服务端的/bus/refresh端点,从而刷新所有客户端的配置,选用该方式比较合适

现使用第二种方式进行配置消息总线动态刷新

配置中心服务端

在配置中心服务端增加依赖

1
2
3
4
5
6
7
8
9
10
<!-- 消息总线进行配置动态刷新 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-kafka</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

增加配置

由于我是用的是kafka进行的传输,所以需要配置kafka配置

1
2
3
4
5
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: test

由于消息总线需要触发/bus/refresh端点,所以需要暴露该端点

1
2
3
4
5
6
# 暴露bus刷新配置端点
management:
endpoints:
web:
exposure:
include: 'bus-refresh'
配置客户端

客户端增加依赖

1
2
3
4
5
6
7
8
9
10
<!-- 消息总线进行配置动态刷新 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-kafka</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

客户端增加配置

1
2
3
4
5
spring:
kafka:
bootstrap-servers: localhost:9092
consumer:
group-id: test
1
2
3
4
5
6
# 端点管理
management:
endpoints:
web:
exposure:
include: "*" # 暴露端点,*表示全部暴露

配置被修改后,需要调用配置中心服务端的/bus/refresh端点来对所有的配置客户端进行配置刷新http://ip:port/actuator/bus-refresh ,使用post请求

如果想要定点配置刷新的话,可以指定某个实例

应用程序的每个实例都有一个服务ID,该服务ID的值可以用spring.cloud.bus.id设置,并且其值应按冒号分隔的标识符列表(从最小到最具体)排列。默认值是根据环境构造的,它是spring.application.nameserver.port(或spring.application.index,如果已设置)的组合。ID的默认值以app:index:id的形式构造,其中:

  • appvcap.application.name(如果存在),或者是spring.application.name
  • indexvcap.application.instance_index(如果存在),依次为spring.application.indexlocal.server.portserver.port0
  • idvcap.application.instance_id(如果存在)或随机值。

HTTP端点接受“ 目的地 ”路径参数,例如/bus-refresh?destination=customers:9000,其中destination`是服务ID。如果该ID由总线上的一个实例拥有,它将处理该消息,而所有其他实例将忽略它

如果想要自动刷新,可以配置git上的webHooks来触发http://ip:port/actuator/bus-refresh

欢迎关注我的其它发布渠道