在微服務架構中,配置文件眾多、管理復雜是常見問題。本文將手把手演示如何將配置集中托管到 Nacos,并在 Spring Cloud Alibaba 項目中實現統一配置管理 + 自動刷新機制。
一、為什么要使用 Nacos 統一配置?
傳統方式下,每個服務都維護自己的 application.yml
,當我們想要修改某個通用配置(如 Redis、JWT 密鑰等)時需要逐個服務更改。缺點明顯:
-
配置分散,難以維護;
-
無法熱更新,需重啟服務;
-
配置不一致易引發 BUG。
? 解決方案:使用 Nacos 配置中心,集中管理配置并實現熱更新。
二、引入依賴(Nacos 配置中心)
在 Spring Boot 項目的 pom.xml
中加入以下依賴:
<!-- Nacos Config 配置中心 -->
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency><!-- Spring Cloud Bootstrap 支持(可選) -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
三、準備配置文件:bootstrap.yml
在每個微服務中新增(或使用)bootstrap.yml
,配置如下:
spring:application:name: trade-service # 服務名,對應Nacos中的Data IDcloud:nacos:config:server-addr: localhost:8848 # Nacos地址file-extension: yaml # 默認配置文件擴展名namespace: public # 命名空間ID(推薦使用dev/test/prod分離)
📌 注意: spring.application.name
會決定從 Nacos 加載的配置名,格式為:{name}.{file-extension}
,例如 trade-service.yaml
。
四、在 Nacos 創建配置文件
登錄 Nacos 控制臺:
-
配置管理 -> 配置列表 -> 新增配置
-
Data ID:trade-service.yaml
-
配置格式:YAML
-
內容示例:
hm:cart:maxSize: 100timeout: 60
五、讀取配置:@ConfigurationProperties 模式
推薦使用結構化配置類方式讀取 Nacos 配置:
@ConfigurationProperties(prefix = "hm.cart")
@Data
public class CartProperties {private Integer maxSize;private Long timeout;
}
并在你的服務中啟用該配置:
@EnableConfigurationProperties(CartProperties.class)
@Service
public class CartServiceImpl implements ICartService {private final CartProperties cartProperties;public CartServiceImpl(CartProperties cartProperties) {this.cartProperties = cartProperties;}
}
六、配置熱更新支持
Spring Cloud Alibaba 中,@ConfigurationProperties + @EnableConfigurationProperties
方式默認支持配置刷新,無需顯式加 @RefreshScope
,這也是你發現“沒有加 @RefreshScope
也能刷新”的原因。
如果你使用的是 @Value
注解讀取配置:
@RefreshScope
@Component
public class PayProperties {@Value("${pay.secret}")private String secret;
}
此時必須使用 @RefreshScope
才能在 /actuator/refresh
被觸發后動態更新。
七、啟用 actuator 手動刷新接口(可選)
如果需要支持通過接口刷新配置,可以添加以下配置:
pom.xml
添加依賴:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
application.yml
中開啟端點:
management:endpoints:web:exposure:include: refresh,health,info
使用 Postman 調用:
POST http://localhost:端口/actuator/refresh
即可手動觸發配置刷新。
八、總結
特性 | @ConfigurationProperties + @EnableConfigurationProperties | @Value + @RefreshScope |
---|---|---|
推薦程度 | ? 推薦,結構化配置、強類型綁定 | ?? 不推薦用于復雜配置 |
是否需手動刷新 | 否,自動生效 | 是,需調用 /actuator/refresh |
是否可嵌套對象 | ? 支持 | ? 不支持 |
🚀 小結
本文完整演示了如何使用 Nacos 實現微服務配置統一管理和熱更新,包括依賴引入、配置文件編寫、Nacos 控制臺創建、配置類綁定和動態刷新原理。掌握這套方法,將大大提升你在微服務項目中的配置管理能力。
如果覺得有幫助,別忘了點贊 + 收藏哦!