配置中心
Spring Cloud 配置中心将应用配置从代码中剥离,支持动态刷新,无需重启服务即可生效。主流方案:Nacos Config(推荐)和 Spring Cloud Config Server(独立部署)。
Nacos Config(推荐)
依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>bootstrap.yml 配置
spring:
application:
name: order-service
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yaml
namespace: dev
group: DEFAULT_GROUP
# 默认 dataId = ${spring.application.name}.${file-extension}
# = order-service.yamlDataId 命名规则
${prefix}-${spring.profiles.active}.${file-extension}
| DataId 示例 | 优先级 | 说明 |
|---|---|---|
order-service-dev.yaml | 高 | 环境专属配置 |
order-service.yaml | 中 | 服务默认配置 |
shared-db.yaml | 低 | 多服务共享配置 |
共享配置
spring:
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yaml
shared-configs:
- data-id: shared-db.yaml
refresh: true
- data-id: shared-redis.yaml
refresh: true
extension-configs: # 优先级高于 shared-configs
- data-id: order-special.yaml
group: ORDER_GROUP
refresh: true动态刷新
@RefreshScope // 配置变更后自动重新注入
@RestController
public class OrderController {
@Value("${order.timeout:5000}")
private int timeout;
@Value("${order.max-retry:3}")
private int maxRetry;
}Spring Cloud Config Server
以 Git 仓库为后端存储的独立配置中心。
Server 端
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>@SpringBootApplication
@EnableConfigServer
public class ConfigServerApp { ... }server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/example/config-repo
default-label: main
search-paths: '{application}'Client 端
# bootstrap.yml
spring:
application:
name: order-service
cloud:
config:
uri: http://localhost:8888
label: main
profile: dev配置文件命名(Git 仓库中)
{application}-{profile}.yml
# 示例:order-service-dev.yml
手动刷新
# 触发单实例刷新
curl -X POST http://localhost:8080/actuator/refresh
# 配合 Spring Cloud Bus 批量刷新(需 RabbitMQ/Kafka)
curl -X POST http://localhost:8888/actuator/busrefresh配置加密
encrypt:
key: my-secret-key# 加密值
curl http://localhost:8888/encrypt -d 'my-db-password'
# 返回:AQA...encrypted...
# 在配置文件中使用
spring.datasource.password: '{cipher}AQA...encrypted...'两种方案对比
| 特性 | Nacos Config | Spring Cloud Config |
|---|---|---|
| 动态刷新 | 长轮询自动推送 | 需调用 /actuator/refresh |
| 配置存储 | Nacos 内置 | Git / SVN / 本地文件 |
| 部署复杂度 | 低(复用注册中心) | 高(需单独部署 + Bus) |
| 版本管理 | 历史版本可回滚 | Git 天然版本管理 |
| 推荐场景 | 国内微服务项目 | 已有 Git 配置管理规范 |
相关链接
Spring Cloud
- Nacos 集成(注册 + 配置)
- 服务注册与发现
- 多环境管理(Namespace 隔离、配置加密)
- 配置管理
- 环境与 Profile
- Spring Cloud 目录