Spring Cloud Config配置中心与刷新机制
请介绍Spring Cloud Config的配置中心架构。配置信息如何存储和传递给微服务?@RefreshScope和Spring Cloud Bus结合如何实现配置动态刷新(无需重启服务)?
回答
专业代码师
Spring Cloud Config架构:
Config Server(配置服务端):
- 从配置仓库(Git/SVN/本地文件系统)拉取配置文件
- 提供RESTful API供客户端获取配置
- URL格式:
/{application}/{profile}[/{label}]
Config Client(配置客户端):
- 启动时从Config Server拉取配置
- 配置自动注入到Environment和@Value字段
配置仓库结构:
config-repo/
├── application.yml # 所有应用共享配置
├── myapp-dev.yml # myapp应用-dev环境
├── myapp-prod.yml # myapp应用-prod环境
└── myapp.yml # myapp应用所有环境
客户端配置:
spring:
application:
name: myapp
cloud:
config:
uri: http://config-server:8888
profile: dev
label: main
动态刷新机制:
-
@RefreshScope + /actuator/refresh:
- 用@RefreshScope标注需要动态刷新的Bean
- 调用POST /actuator/refresh端点刷新上下文
- 所有@RefreshScope Bean重建,重新注入最新配置
- 缺点:每台服务需单独触发,不适用于多实例
-
Spring Cloud Bus(消息总线):
# 引入spring-cloud-starter-bus-amqp或spring-cloud-starter-bus-kafka
# Git Webhook触发:
# POST /actuator/bus-refresh
# Bus将刷新事件广播到所有连接到同一条消息队列的微服务实例
- 流程:
- Git仓库配置变更,配置Webhook通知Config Server
- Config Server调用POST /actuator/bus-refresh
- Bus广播RefreshRemoteApplicationEvent到所有服务
- 所有服务实例自动刷新配置(无需重启)
当前趋势:Nacos配置中心原生支持动态刷新(基于长轮询),比Spring Cloud Config更简便。