文章目錄
- 為什么要使用配置中心?
- 一、引入nacos-config配置中心
- 二、配置bootstrap.properties元資料
- 三、動態獲取配置
- 四、在配置中心添加資料集
- 五、配置中心進階使用
- 1.命名空間
- 2.配置 集/ID/分組
- 3.載多個配置集
Nacos作為配置中心檔案地址:https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md
為什么要使用配置中心?
引入配置中心最重要的一點是:可以在系統運行時(runtime)動態調整組態檔!

一、引入nacos-config配置中心
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
二、配置bootstrap.properties元資料
官方檔案要求我們創建
bootstrap.properties組態檔,配置 Nacos Config 元資料,
- 注:使用nacos時,
bootstrap.properties會優先于application.properties檔案,
spring.application.name=gulimall-coupon
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
三、動態獲取配置
動態獲取配置需要在Controller中加入
@RefreshScope注解,
@RefreshScope
public class CouponController {
...
@Value("${coupon.user.name}")
private String name;
@Value("${coupon.user.age}")
private String age;
}
四、在配置中心添加資料集
Data ID的默認名:
微服務名.properties

之后,只需要在nacos配置中心對配置進行修改發布即可動態修改資料,無需重新為微服務打包發布了,

注意:如果配置中心和專案組態檔中都配置了相同的項,則優先 使用配置中心的配置!
五、配置中心進階使用
1.命名空間
- 命名空間可以用來做
配置隔離: 不同的命名空間下, 可以存在相同的 Group 或 Data ID 的
配置,- 命名空間可以
基于環境進行環境隔離:開發、測驗、生產,各自使用不同的命名空間,- 命名空間也可以
基于微服務進行環境隔離:不同微服務使用各自的命名空間,
可以在bootstrap.properties中設定使用的命名空間,下圖以專案真實上線時為例:

也可以在每一個微服務之間互相隔離配置,每一個微服務都創建自己的命名空間,只加載自己命名空間下的所有配置,
2.配置 集/ID/分組
配置集:一組相關或者不相關的配置項的集合稱為配置集,
配置集 ID:類似組態檔名,在nacos中即是Data ID,
配置分組:默認所有的配置及都屬于DEFAULT_GROUP,專案在不同時期可以使用不同的配置分組,例如雙11,雙12時就可以切換性能更高的配置,
配置分組可以在bootstrap.properties使用spring.cloud.nacos.config.group=配置分組名進行配置,
在谷粒商城專案中:
微服務隔離:每個微服務創建自己的命名空間,環境隔離:使用配置分組區分環境,區分dev,test,prod環境,
3.載多個配置集
可以將配置拆分成多個,同時加載,
- 任何組態檔都可以放在配置中心中,只需要在
bootstrap.properties中說明加載配置中心中哪些組態檔即可,并且優先使用配置中心,

spring.cloud.nacos.config.ext-config[0].data-id=datasource.yml
spring.cloud.nacos.config.ext-config[0].group=dev
spring.cloud.nacos.config.ext-config[0].refresh=true
spring.cloud.nacos.config.ext-config[1].data-id=mybatis.yml
spring.cloud.nacos.config.ext-config[1].group=dev
spring.cloud.nacos.config.ext-config[1].refresh=true
spring.cloud.nacos.config.ext-config[2].data-id=other.yml
spring.cloud.nacos.config.ext-config[2].group=dev
spring.cloud.nacos.config.ext-config[2].refresh=true
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/258697.html
標籤:其他
