Spring Cloud 整合 nacos 實現動態配置中心

上一篇文章講解了Spring Cloud 整合 nacos 實現服務注冊與發現,nacos除了有服務注冊與發現的功能 , 還有提供動態配置服務的功能 。本文主要講解Spring Cloud 整合nacos實現動態配置服務 。主要參考官方部署手冊點我 。
前提條件先下載nacos并啟動nacos服務 。操作步驟詳見Nacos 快速入門 。
整合步驟1. 添加依賴<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId><version>2.2.7.RELEASE</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.2.12.RELEASE</version></dependency>

版本nacos2.1.x.RELEASE 對應的是 Spring Boot 2.1.x 版本 。版本 2.0.x.RELEASE 對應的是 Spring Boot 2.0.x 版本,版本 1.5.x.RELEASE 對應的是 Spring Boot 1.5.x 版本 。版本不匹配的話,會出現很多莫名其妙的問題 。nacos依賴版本要和nacos服務端版本要一致 。
2. 新建 nacos 配置在nacos控制臺添加配置列表:
Spring Cloud 整合 nacos 實現動態配置中心

文章插圖
設置dataIdnacos-config,文件后綴為Properties , 設置內容user.name=jack
Spring Cloud 整合 nacos 實現動態配置中心

文章插圖
3. bootstrap.properties 配置在application.yml同目錄下創建bootstrap.yml文件 , 并配置Nacos服務地址以及namespace(沒有就不需要配置):
spring:application:name: nacos-config-clientcloud:nacos:config:server-addr: 127.0.0.1:8848namespace: 68468122-8955-45ee-a5b7-3d87972325b14. 配置dataIddataId對應步驟2里面的dataId , 有兩種配置方式,一種是官方自動構建dataId,另一種是指定dataId 。
4.1 自動配置 dataId在Nacos Spring Cloud中,dataId的完整格式如下:
${prefix}-${spring.profiles.active}.${file-extension}
  • prefix 默認為 spring.application.name 的值,也可以通過配置項 spring.cloud.nacos.config.prefix來配置 。
  • spring.profiles.active 即為當前環境對應的 profile 。注意:當 spring.profiles.active 為空時 , 對應的連接符 - 也將不存在,dataId 的拼接格式變成 ${prefix}.${file-extension}
  • file-exetension 為配置內容的數據格式,可以通過配置項 spring.cloud.nacos.config.file-extension 來配置 。目前只支持 propertiesyaml 類型 。
比如項目名稱為nacos-config-client,當前環境為test,格式文件為properties,那就需要新建一個dataIdnacos-config-client.properties配置 。
4.2 手動設置 dataId在NacosConfigProperties類里面name字段就是配置dataId
public class NacosConfigProperties {/*** nacos config dataId name.*/ private String name;//省略其他配置}bootstrap.yml添加spring.cloud.nacos.config.name就可以設置dataId 。
5.獲取數據通過@Value就能獲取配置文件的數據:
@Component@RefreshScopepublic class TestConfig {@Value(value = "https://www.huyubaike.com/biancheng/${user.name:null}")private String test;public String getTest(){return test;}要實現配置的自動更新,需要添加Spring Cloud原生注解 @RefreshScope 。controller直接調用即可:
@RestControllerpublic class TestController {@Autowiredprivate TestConfig testConfig;@GetMapping("/config")public String testConfig(){String config = testConfig.getTest();return config;}}如果想通過@NacosValues注解獲取數據 , 需要引入nacos-config-spring-boot-starter依賴:
<dependency><groupId>com.alibaba.boot</groupId><artifactId>nacos-config-spring-boot-starter</artifactId><version>0.2.7</version></dependency>總結