Nacos 配置中心
Nacos 配置中心简介
Nacos 配置中心提供配置集中管理、动态刷新、版本控制等功能,支持多环境、多租户配置隔离。
核心优势
- 配置集中管理:统一管理所有服务的配置
- 配置动态刷新:无需重启服务即可更新配置
- 版本管理:支持配置版本控制和回滚
- 环境隔离:支持多环境配置隔离
- 灰度发布:支持配置灰度发布
- 配置监听:实时监听配置变化
配置模型
┌─────────────────────────────────────────┐
│ Data ID │
│ (配置文件唯一标识) │
└─────────────────────────────────────────┘
│
┌─────────┼─────────┐
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│ Group │ │ Group │ │ Group │
│DEFAULT │ │ V1 │ │ V2 │
└────────┘ └────────┘ └────────┘
│
▼
┌─────────────────────────────────────────┐
│ Namespace │
│ (环境隔离:dev/test/prod) │
└─────────────────────────────────────────┘
快速开始
1. 添加依赖
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
2. 配置 bootstrap.yml
spring:
application:
name: user-service
cloud:
nacos:
config:
server-addr: localhost:8848
namespace: public
group: DEFAULT_GROUP
file-extension: yaml
refresh-enabled: true
# 共享配置
shared-configs:
- data-id: common.yaml
group: DEFAULT_GROUP
refresh: true
# 扩展配置
extension-configs:
- data-id: redis.yaml
group: DEFAULT_GROUP
refresh: true
3. 启用配置中心
@SpringBootApplication
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
4. 读取配置
@RestController
@RefreshScope // 支持配置动态刷新
public class UserController {
@Value("${user.timeout:3000}")
private Integer timeout;
@Autowired
private Environment environment;
@GetMapping("/config")
public String getConfig() {
String value = environment.getProperty("user.timeout");
return "timeout: " + value;
}
}
配置加载优先级
Nacos 配置加载优先级(从高到低):
- 服务私有配置:
{spring.application.name}.{file-extension} - 应用名 + 环境配置:
{spring.application.name}-{profile}.{file-extension} - 应用名 + 环境 + 分组配置:
{spring.application.name}-{profile}-{group}.{file-extension} - 扩展配置:
extension-configs - 共享配置:
shared-configs - 本地配置:
application-{profile}.yml - 本地默认配置:
application.yml
配置示例
# 优先级示例(假设应用名为 user-service,环境为 dev)
# 1. user-service-dev.yaml (最高优先级)
# 2. user-service.yaml
# 3. extension-configs 配置
# 4. shared-configs 配置
# 5. application-dev.yaml (本地)
# 6. application.yaml (本地,最低优先级)
配置动态刷新
@RefreshScope 注解
@Component
@RefreshScope
public class ConfigBean {
@Value("${config.value:default}")
private String configValue;
// getter/setter
}
配置变更监听器
@Component
public class ConfigChangeListener {
@NacosConfigListener(dataId = "user-service.yaml")
public void onConfigChange(String config) {
log.info("配置发生变化:{}", config);
// 处理配置变更逻辑
}
}
手动刷新配置
@RestController
public class ConfigController {
@Autowired
private ContextRefresher refresher;
@PostMapping("/refresh")
public Set<String> refresh() {
return refresher.refresh();
}
}
多环境配置
环境隔离方案
# bootstrap-dev.yml
spring:
cloud:
nacos:
config:
namespace: dev-namespace-id
group: DEFAULT_GROUP
# bootstrap-test.yml
spring:
cloud:
nacos:
config:
namespace: test-namespace-id
group: DEFAULT_GROUP
# bootstrap-prod.yml
spring:
cloud:
nacos:
config:
namespace: prod-namespace-id
group: DEFAULT_GROUP
激活环境
# 方式 1:命令行参数
java -jar app.jar --spring.profiles.active=dev
# 方式 2:环境变量
export SPRING_PROFILES_ACTIVE=dev
java -jar app.jar
# 方式 3:配置文件
spring.profiles.active=dev
配置加密
内置加密支持
Nacos 支持配置加密,使用 {cipher} 前缀标识加密值:
spring:
datasource:
url: jdbc:mysql://localhost:3306/user_db
username: root
password: "{cipher}加密后的密码"
自定义加密解密
@Component
public class CustomCipher implements CipherService {
@Override
public String encrypt(String content) {
// 自定义加密逻辑
return Base64.getEncoder().encodeToString(content.getBytes());
}
@Override
public String decrypt(String content) {
// 自定义解密逻辑
return new String(Base64.getDecoder().decode(content));
}
}
配置版本管理
版本控制
Nacos 控制台提供配置版本管理功能:
- 历史版本列表:查看配置变更历史
- 版本对比:对比不同版本的差异
- 版本回滚:一键回滚到历史版本
配置变更审计
@Component
public class ConfigAuditListener {
@NacosConfigListener(dataId = "user-service.yaml")
public void onConfigChange(String config) {
// 记录配置变更审计日志
AuditLog log = new AuditLog();
log.setDataId("user-service.yaml");
log.setChangeTime(LocalDateTime.now());
log.setContent(config);
auditService.save(log);
}
}
配置灰度发布
基于分组的灰度
# 灰度环境配置
spring:
cloud:
nacos:
config:
group: GRAY_GROUP # 灰度分组
基于元数据的灰度
@Component
public class GrayConfig {
@Value("${gray.enabled:false}")
private Boolean grayEnabled;
@Value("${gray.percentage:0}")
private Integer grayPercentage;
public boolean isGrayRequest(String userId) {
if (!grayEnabled) {
return false;
}
int hash = Math.abs(userId.hashCode());
return hash % 100 < grayPercentage;
}
}
生产实践
1. 配置分类管理
# 共享配置:common.yaml
spring:
redis:
host: ${redis.host}
port: ${redis.port}
rabbitmq:
host: ${rabbitmq.host}
port: ${rabbitmq.port}
# 应用配置:user-service.yaml
user:
timeout: 3000
max-retries: 3
2. 配置预检
@Component
public class ConfigValidator {
@PostConstruct
public void validate() {
String dbUrl = System.getenv("DB_URL");
if (StringUtils.isEmpty(dbUrl)) {
throw new ConfigException("数据库配置不能为空");
}
}
}
3. 配置备份
@Component
public class ConfigBackup {
@Autowired
private ConfigService configService;
@Scheduled(cron = "0 0 2 * * ?") # 每天凌晨 2 点备份
public void backup() {
List<String> dataIds = getDataIds();
for (String dataId : dataIds) {
String content = configService.getConfig(dataId, "DEFAULT_GROUP", 5000);
backupToFile(dataId, content);
}
}
}
4. 配置变更通知
@Component
public class ConfigChangeNotifier {
@NacosConfigListener(dataId = "user-service.yaml")
public void onConfigChange(String config) {
// 发送配置变更通知
Notification notification = new Notification();
notification.setTitle("配置变更通知");
notification.setContent("user-service.yaml 配置已更新");
notificationService.send(notification);
}
}
常见问题
1. 配置不生效
问题:配置更新后未生效
排查步骤:
- 检查是否添加
@RefreshScope注解 - 检查配置优先级是否正确
- 检查配置文件名是否正确
- 查看 Nacos 控制台配置是否发布成功
2. 配置刷新失败
问题:配置刷新时报错
解决方案:
- 检查 Bean 是否支持刷新
- 避免在构造函数中使用配置
- 使用
Environment获取配置
3. 配置加载顺序
问题:配置加载顺序不符合预期
解决方案:
- 调整
bootstrap.yml配置顺序 - 使用
@Order注解控制配置类加载顺序 - 检查配置优先级规则
总结
Nacos 配置中心提供了配置集中管理、动态刷新、版本控制等核心功能。
通过合理使用命名空间、分组、共享配置等特性,可以实现灵活的配置管理策略。
在生产环境中,建议做好配置分类管理,实施配置变更审计,并建立配置备份机制。