SpringBoot使用Nacos配置中心
摘要: SpringBoot如何使用阿里巴巴Nacos做配置中心
本文介紹SpringBoot如何使用阿里巴巴Nacos做配置中心。
1.Nacos簡介
Nacos是阿里巴巴集團開源的一個易於使用的平臺,專為動態服務發現,配置和服務管理而設計。它可以幫助您輕鬆構建雲本機應用程式和微服務平臺。
Nacos基本上支援現在所有型別的服務,例如,Dubbo / gRPC服務,Spring Cloud RESTFul服務或Kubernetes服務。
尤其是使用Eureka註冊中心的,並且擔心Eureka閉源的開發者們,可以將註冊中心修改為Nacos,本文主要介紹Nacos配置中心的使用。
Nacos官網如下圖所示,官網地址 https://nacos.io/zh-cn/

2.Nacos安裝
Nacos安裝可以採用如下兩種方式:
1.官網下載穩定版本解壓使用。
2.下載原始碼編譯使用,目前最新的版本是0.8.0版本。
本文簡單介紹一下第二種方式,到Nacos的穩定版本下載地址 https://github.com/alibaba/nacos/releases ,下載最新版,本文下的是tag.gz檔案,下載後解壓即安裝完成,然後進入解壓目錄後的bin目錄執行如下命令啟動Nacos。
shstartup.sh-mstandalone
啟動可以看到控制檯如圖所示,埠號是8848(好像是因為珠穆朗瑪峰的高度),版本0.8.0等等資訊。

3.SpringBoot使用Nacos
接下來,建立專案,專案中加入使用Nacos配置中心的依賴nacos-config-spring-boot-starter,完整pom檔案如程式碼所示。
<?xml version="1.0"encoding="UTF-8"?>4.0.0org.springframework.bootspring-boot-starter-parent2.1.1.RELEASE<!-- lookup parent from repository -->com.dalaoyangspringboot2_nacos_config0.0.1-SNAPSHOTspringboot2_nacos_configspringboot2_nacos_config1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-devtoolsruntimeorg.springframework.bootspring-boot-starter-testtest<!-- https://mvnrepository.com/artifact/com.alibaba.boot/nacos-config-spring-boot-starter -->com.alibaba.bootnacos-config-spring-boot-starter0.2.1org.springframework.bootspring-boot-maven-plugin
配置檔案中需要配置Nacos服務的地址,如下所示。
spring.application.name=springboot2-nacos-config
nacos.config.server-addr=127.0.0.1:8848
在啟動類,加入@NacosPropertySource註解其中包含兩個屬性,如下:
dataId:這個屬性是需要在Nacos中配置的Data Id。
autoRefreshed:為true的話開啟自動更新。
在使用Nacos做配置中心後,需要使用@NacosValue註解獲取配置,使用方式與@Value一樣,完整啟動類程式碼如下所示。
packagecom.dalaoyang;importcom.alibaba.nacos.api.config.annotation.NacosValue;importcom.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RestController;@SpringBootApplication@NacosPropertySource(dataId ="springboot2-nacos-config", autoRefreshed =true)@RestControllerpublicclassSpringboot2NacosConfigApplication{publicstaticvoidmain(String[] args){ SpringApplication.run(Springboot2NacosConfigApplication.class, args); }@NacosValue(value ="${nacos.test.propertie:123}", autoRefreshed =true)privateString testProperties;@GetMapping("/test")publicStringtest(){returntestProperties; }}
由於本文只是簡單示例使用Nacos做配置中心,所以將啟動類加了一個MVC方法,作為輸出配置資訊進行測試,這個測試的配置給了一個預設值123,啟動專案,訪問 http://localhost:8080/test ,可以看到如下所示:

4.使用Nacos修改配置
訪問Nacos服務, http://localhost:8848/nacos/#/login ,預設情況使用者名稱密碼都是nacos,登入頁如圖所示。

登入後如圖所示。

接下來點選右側加號,新增我們剛剛建立的data id 的服務,並將配置由123修改為111,如圖所示。

然後點選右下角釋出按鈕,再次訪問 http://localhost:8080/test 如圖所示。

到這裡SpringBoot使用Nacos配置中心就完成了,感興趣可以檢視原始碼仔細研究。