Spring Cloud Config
Spring Cloud Config
Spring Cloud Config 为分布式系统提供集中化外部配置管理,支持 Git、SVN 等后端存储。
适用场景
微服务架构的配置管理、多环境配置隔离、动态刷新配置。
核心组件
| 组件 | 说明 |
|---|---|
| Config Server | 配置服务器,集中存储配置,提供读取接口 |
| Config Client | 客户端(微服务),从 Server 获取配置 |
Config Server
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>启动类添加 @EnableConfigServer,配置 Git 仓库:
spring:
cloud:
config:
server:
git:
uri: https://github.com/user/config-repo
default-label: mainConfig Client
使用 bootstrap.yml 确保应用启动早期获取配置:
spring:
application:
name: service-goods
cloud:
config:
uri: http://localhost:8888
fail-fast: true动态刷新
客户端添加 @RefreshScope,通过 /actuator/refresh 端点触发刷新:
@RefreshScope
@RestController
public class ConfigController {
@Value("${custom.value}")
private String customValue;
}提示
配合 SpringCloudBus 通过 /bus/refresh 实现配置变更自动广播到所有实例,无需逐个重启。
常见问题
| 问题 | 排查方向 |
|---|---|
| 配置获取失败 | 检查 Server 运行状态、bootstrap.yml、Git 仓库地址和分支 |
| 动态刷新不生效 | 确认 @RefreshScope、/actuator/refresh 端点、配置已推送 Git |