一、Nacos Config簡介
是什么?
-
Nacos:Dynamic Naming and Configuration Service。
-
Nacos:其實就是 Eureka 服務注冊中心 + Config 服務配置中心 + Bus消息總線的組合。
二、基礎配置
1)build.gradle項目依賴
dependencies { compile group: 'org.springframework.boot', name: 'spring-boot-starter-web' compile group: 'org.springframework.boot', name: 'spring-boot-starter-actuator' compile group: 'com.alibaba.cloud', name: 'spring-cloud-starter-alibaba-nacos-config', version: '2.1.0.RELEASE' compile group: 'com.alibaba.cloud', name: 'spring-cloud-starter-alibaba-nacos-discovery', version: '2.1.0.RELEASE' }
2)為什么要配置兩個配置文件?
Nacos 同 Spring Cloud Config 在項目初始化時,要保證先從配置中心進行配置拉取,拉取配置后,才能保證項目的正常啟動。Spring Boot 中配置文件的加載是存在優先級順序的,bootstrap 優先級高於 application。

server: port: 7071 spring: application: name: config-client-nacos cloud: nacos: discovery: server-addr: 127.0.0.1:8848 #指定Nacos服務注冊中心地址 config: server-addr: 127.0.0.1:8848 #指定Nacos服務配置中心地址 file-extension: yaml #指定yaml格式的配置(原先GitHub上的配置文件)

spring:
profiles:
active: dev #表示激活開發環境

package org.wesson.cloudalibaba.nacos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @EnableDiscoveryClient @SpringBootApplication public class ConfigClientNacosApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientNacosApplication.class, args); } }
4)Controller
通過 Spring Cloud 原生注解 @RefreshScope

package org.wesson.cloudalibaba.nacos.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RefreshScope // 支持Nacos的動態刷新功能 public class ConfigNacosController { @Value("${config.info}") private String configInfo; @GetMapping("/getInfo") public String getConfigInfo() { return configInfo; } }
5)在Nacos中添加配置信息
理論,Nacos 中的匹配規則
公式:
${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
用例:
config-client-nacos-dev.yaml
注意:嚴格按照官網公式,不要讓 spring.profile.active
為空,不然會出現莫名其妙的問題。
實操,新建配置
小總結
6)測試
啟動前需要在 Nacos 客戶端配置列表菜單下有對應的yaml配置文件
Step1:
Step2:運行 config-client-nacos 啟動類,端口為7071
Step3:調用接口查看配置信息,訪問http://localhost:7071/getInfo,結果如下:
成功獲取 Nacos 客戶端配置列表 config-client-nacos-dev.yaml 配置文件中的內容。
三、自帶動態刷新配置
不需要添加任何相關的 Bus 消息總線依賴,直接編輯修改 Nacos 客戶端配置列表中的 yaml 配置文件版本發布即可:
點擊發布后,會有一個當前值與原始值的對比效果,然后確認發布:
根本不需要重啟任何服務以及原先發送的 POST 請求。再次調用查看配置的接口,就會發現配置成功實現動態刷新功能了:
不得不說,阿里巴巴的 Nacos 技術還是還是非常成熟的,相當於完全代替了 Eureka、Config 與 Bus 三個組件。

spring:
cloud:
nacos:
config:
refresh:
enabled: false