使用/refresh
端点手动刷新配置
给客户端的 Controller 添加@RefreshScope
注解,即可用POST
访问/refresh
端点刷新配置。
使用Sping Cloud Bus
自动刷新配置
为什么使用Sping Cloud Bus
前面使用/refresh
端点手动刷新配置,但是如果所有微服务节点的配置都需要手动去刷新的话,那必然是一个繁琐的工作,并且随着系统的不断扩张,会变得越来越难以维护。因此,实现配置的自动刷新是很有必要的。
Sping Cloud Bus
简介
Spring Cloud Bus
提供了批量刷新配置的机制,它使用轻量级的消息代理(例如 RabbitMQ、Kafka 等)连接分布式系统的节点,这样就可以通过Spring Cloud Bus
广播配置的变化或者其他的管理指令。架构如图:
实现自动刷新
启动 rabbitMQ 服务。
pom
添加依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
的 Controller 添加
@RefreshScope
注解。在
bootstrap.yml
中配置:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
- 启动服务,
POST
请求/bus/refresh
端点,会刷新配置文件。(可通过 Git 仓库的WebHooks
实现自动刷新)。
局部刷新
可通过/bus/refresh
端点的 destination 参数来定位要刷新的应用程序。
例如/bus/refresh?destination=ApplicationContextID
。
跟踪总线事件
设置spring.cloud.bus.trace.enabled=true
,在/bus/refresh
被请求之后,访问/trace
端点可以访问总线事件。