Spring Cloud Config 配置中心管理
核心架构
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Config Client │ │ Config Server │ │ Git Repository│
│ (Application) │◄───│ (localhost:8888)│◄───│ (配置存储) │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Config Server 搭建
Maven 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
主启动类
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
application.yml 配置
server:
port: 8888
spring:
application:
name: config-server
# Git 后端配置存储
cloud:
config:
server:
git:
uri: https://github.com/your-org/config-repo # Git仓库地址
search-paths: '{application}' # 搜索路径
default-label: main # 默认分支
username: ${GIT_USERNAME} # Git用户名(如需认证)
password: ${GIT_PASSWORD} # Git密码
clone-on-start: true # 启动时克隆
force-pull: true # 强制拉取
# 本地文件系统(非Git环境)
# native:
# search-locations: classpath:/config
配置文件命名规则
{application}-{profile}.yml
示例:

user-service-dev.ymluser-service-prod.ymluser-service.yml(默认配置)application.yml(公共配置)
Config Client 配置
Maven 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
bootstrap.yml(必须使用bootstrap)
spring:
application:
name: user-service
cloud:
config:
uri: http://localhost:8888 # Config Server 地址
fail-fast: true # 启动失败快速报错
retry:
initial-interval: 1000 # 初始重试间隔
multiplier: 1.5 # 重试间隔倍数
max-attempts: 5 # 最大重试次数
# 配置发现(配合Eureka)
# discovery:
# enabled: true
# service-id: config-server
profiles:
active: dev # 激活的环境
配置刷新机制
手动刷新(@RefreshScope)
@RestController
@RefreshScope // 关键注解
public class ConfigController {
@Value("${user.max-age:100}")
private Integer maxAge;
@GetMapping("/config")
public String getConfig() {
return "Max Age: " + maxAge;
}
}
触发刷新:
curl -X POST http://localhost:8081/actuator/refresh
自动刷新(Spring Cloud Bus)
依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
配置:
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
management:
endpoints:
web:
exposure:
include: bus-refresh
触发全局刷新:
curl -X POST http://localhost:8888/actuator/bus-refresh
安全配置
对称加密
Config Server 配置:
encrypt: key: your-secret-key-12345
加密属性值:
curl -X POST http://localhost:8888/encrypt -d "your-plain-text" # 返回: 加密后的密文
配置文件中使用:
database:
password: '{cipher}AQA...加密后的密文...'
配置安全认证
spring:
security:
user:
name: config-admin
password: ${CONFIG_PASSWORD}
配置管理最佳实践
配置文件结构
config-repo/
├── application.yml # 公共配置
├── user-service.yml # 默认配置
├── user-service-dev.yml # 开发环境
├── user-service-prod.yml # 生产环境
├── order-service.yml
└── ...
优先级规则
应用特定配置 > Profile配置 > 默认配置 > 公共配置
bootstrap.yml > application.yml
配置版本管理
spring:
cloud:
config:
server:
git:
# 支持标签/分支版本
default-label: v1.0.0
多环境配置示例
dev:
# user-service-dev.yml server: port: 8081 database: url: jdbc:mysql://localhost:3306/user_dev username: dev_user redis: host: localhost
prod:
# user-service-prod.yml server: port: 80 database: url: jdbc:mysql://prod-db:3306/user_prod username: prod_user redis: host: prod-redis-cluster
监控与运维
健康检查
management:
endpoints:
web:
exposure:
include: health,info,env,refresh
配置审计
@EventListener
public void handleRefresh(RefreshScopeRefreshedEvent event) {
log.info("配置已刷新: {}", event.getSource());
// 记录审计日志
}
配置回滚
# 回滚到特定版本 git checkout <commit-hash> -- <config-file> # 强制重启刷新 curl -X POST http://localhost:8888/actuator/restart
常见问题解决
配置无法加载
# 检查Config Server状态 curl http://localhost:8888/user-service/dev # 查看客户端环境 curl http://localhost:8081/actuator/env
配置刷新不生效
- 确认添加
@RefreshScope - 检查
management.endpoints.web.exposure.include配置 - 确认请求方法为
POST
安全加固
# 禁止明文配置
spring:
cloud:
config:
server:
encrypt:
enabled: true
微服务配置示例
# user-service-dev.yml
spring:
datasource:
url: ${DB_URL:jdbc:mysql://localhost:3306/user}
username: ${DB_USER:root}
password: ${DB_PASSWORD:password}
redis:
host: ${REDIS_HOST:localhost}
port: 6379
rabbitmq:
host: ${RABBIT_HOST:localhost}
port: 5672
server:
port: 8081
logging:
level:
com.example: DEBUG
feign:
client:
config:
default:
connect-timeout: 5000
read-timeout: 5000
通过合理使用 Spring Cloud Config,可以实现微服务配置的集中管理、动态刷新、版本控制和环境隔离,极大地提高系统的可维护性和灵活性。