Nacos 配置中心
TIP
Nacos 配置中心支持配置的集中管理、动态刷新和版本回滚,实现配置的运行时热更新。
配置管理流程
Nacos 控制台 → 新建配置
↓
配置变更 → 推送通知
↓
客户端接收 → 动态刷新
↓
应用生效客户端配置
yaml
spring:
application:
name: user-service
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
file-extension: yaml
namespace: public
group: DEFAULT_GROUP
refresh-enabled: true
config:
import:
- nacos:user-service.yamlNacos 控制台配置
Data ID: user-service.yaml
Group: DEFAULT_GROUP
格式: YAML
# 配置内容
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/demo
username: root
password: 123456动态刷新配置
java
@RestController
@RefreshScope // 关键注解,实现配置动态刷新
public class ConfigController {
@Value("${app.useFeatureX:false}")
private boolean useFeatureX;
@GetMapping("/feature")
public String getFeature() {
return "Feature X is " + (useFeatureX ? "enabled" : "disabled");
}
}
// 或者使用 @ConfigurationProperties
@Component
@RefreshScope
@ConfigurationProperties(prefix = "order")
@Data
public class OrderConfig {
private int timeout = 5000;
private int maxRetry = 3;
}多环境配置
yaml
# 通过 namespace 或 group 隔离环境
spring:
cloud:
nacos:
config:
namespace: dev # 开发环境
# namespace: test # 测试环境
# namespace: prod # 生产环境配置优先级
应用本地配置 < Nacos 配置 < 命令行参数TIP
- 通用配置放在 Nacos,敏感配置(密码等)建议加密或使用环境变量
- 使用 @RefreshScope 的 Bean 在配置变更时会重新创建,注意副作用