Spring Cloud Config配置中心
约 1215 字大约 4 分钟
spring-cloudconfig
2025-03-30
概述
Spring Cloud Config 提供了分布式系统中的外部化配置管理方案。它由 Config Server(服务端)和 Config Client(客户端)组成,支持 Git、SVN、本地文件系统等多种后端存储,提供配置加密、版本管理和动态刷新等企业级特性。
架构设计
Config Server 搭建
基于 Git 后端
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}# Config Server - application.yml
server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/myorg/config-repo
default-label: main
search-paths: '{application}'
clone-on-start: true
timeout: 10
# 私有仓库认证
username: ${GIT_USERNAME}
password: ${GIT_PASSWORD}
# 多仓库配置
repos:
development:
pattern: '*/dev'
uri: https://github.com/myorg/config-repo-dev
production:
pattern: '*/prod'
uri: https://github.com/myorg/config-repo-prodGit 仓库结构
config-repo/
├── application.yml # 所有应用的公共配置
├── application-dev.yml # 所有应用的dev环境配置
├── application-prod.yml # 所有应用的prod环境配置
├── user-service.yml # user-service的默认配置
├── user-service-dev.yml # user-service的dev环境配置
├── user-service-prod.yml # user-service的prod环境配置
├── order-service.yml
├── order-service-dev.yml
└── order-service-prod.yml配置文件优先级
基于本地文件系统(Native)
spring:
profiles:
active: native
cloud:
config:
server:
native:
search-locations: file:///etc/config-repo,classpath:/config-repoConfig Client 配置
# Config Client - application.yml
spring:
application:
name: user-service
profiles:
active: dev
config:
import: optional:configserver:http://localhost:8888
cloud:
config:
fail-fast: true
retry:
initial-interval: 1000
max-interval: 5000
max-attempts: 6
multiplier: 1.5客户端启动时会从 Config Server 拉取以下配置(按优先级从高到低):
GET /user-service/dev/main
返回的配置来源:
1. user-service-dev.yml
2. user-service.yml
3. application-dev.yml
4. application.yml配置加密
Config Server 支持对敏感配置进行加密存储。
对称加密
# Config Server
encrypt:
key: ${ENCRYPT_KEY} # 对称加密密钥# 加密
curl -X POST http://localhost:8888/encrypt -d 'my-secret-password'
# 返回: AQBlahBlah...加密后的值
# 解密
curl -X POST http://localhost:8888/decrypt -d 'AQBlahBlah...'在配置文件中使用加密值:
# config-repo/user-service.yml
spring:
datasource:
username: admin
password: '{cipher}AQBlahBlah...加密后的值'非对称加密(RSA)
encrypt:
key-store:
location: classpath:server.jks
password: ${KEYSTORE_PASSWORD}
alias: config-server-key
secret: ${KEY_SECRET}@RefreshScope 动态刷新
@RestController
@RefreshScope
public class DynamicConfigController {
@Value("${app.feature.new-ui:false}")
private boolean newUiEnabled;
@Value("${app.rate-limit:100}")
private int rateLimit;
@GetMapping("/config/feature-flags")
public Map<String, Object> getFeatureFlags() {
return Map.of(
"newUiEnabled", newUiEnabled,
"rateLimit", rateLimit
);
}
}手动触发刷新:
# 刷新单个实例
POST http://user-service:8080/actuator/refresh
# 返回变更的配置key列表
["app.feature.new-ui", "app.rate-limit"]Spring Cloud Bus 批量刷新
引入 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: busrefresh触发全量刷新或指定服务刷新:
# 刷新所有服务
POST /actuator/busrefresh
# 仅刷新 user-service 的所有实例
POST /actuator/busrefresh/user-service:**Profile 管理策略
// 多环境配置最佳实践
@Configuration
public class DataSourceConfig {
@Bean
@Profile("dev")
public DataSource devDataSource() {
// H2 内存数据库
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
@Bean
@Profile("prod")
public DataSource prodDataSource(
@Value("${spring.datasource.url}") String url,
@Value("${spring.datasource.username}") String username,
@Value("${spring.datasource.password}") String password) {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(url);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}
}Vault 集成
spring:
cloud:
config:
server:
vault:
host: vault.example.com
port: 8200
scheme: https
authentication: TOKEN
token: ${VAULT_TOKEN}
default-key: application
backend: secret
profile-separator: /Vault 中的 secret 路径对应关系:
secret/application → 所有应用公共secret
secret/user-service → user-service的secret
secret/user-service/prod → user-service prod环境的secret高可用部署
# Config Server 高可用 - 注册到服务发现
spring:
cloud:
config:
server:
git:
uri: https://github.com/myorg/config-repo
discovery:
enabled: true
service-id: config-server
eureka:
client:
service-url:
defaultZone: http://eureka:8761/eureka/# Config Client - 通过服务发现找到Config Server
spring:
cloud:
config:
discovery:
enabled: true
service-id: config-server
fail-fast: true总结
Spring Cloud Config 提供了集中化的外部配置管理能力:Git 后端实现配置版本化,加密机制保护敏感数据,@RefreshScope 和 Spring Cloud Bus 实现运行时配置热更新。在微服务架构中,Config 与服务发现组件配合使用可实现高可用部署。对于更复杂的需求,也可以结合 Vault 进行敏感信息管理,或迁移到 Nacos 等更现代的配置中心方案。
贡献者
更新日志
2026/3/14 13:09
查看所有更新日志
9f6c2-feat: organize wiki content and refresh site setup于