上一篇文章讲解了Spring Cloud 整合 nacos 实现服务注册与发现,nacos除了有服务注册与发现的功能,还有提供动态配置服务的功能。本文主要讲解Spring Cloud 整合nacos实现动态配置服务。主要参考官方部署手册点我。
先下载nacos并启动nacos服务。操作步骤详见Nacos 快速入门。
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config
2.2.7.RELEASE
org.springframework.boot
spring-boot-starter-web
2.2.12.RELEASE
版本
nacos2.1.x.RELEASE 对应的是Spring Boot2.1.x 版本。版本 2.0.x.RELEASE 对应的是 Spring Boot 2.0.x 版本,版本 1.5.x.RELEASE 对应的是Spring Boot1.5.x 版本。版本不匹配的话,会出现很多莫名其妙的问题。nacos依赖版本要和nacos服务端版本要一致。
在nacos控制台添加配置列表:

设置dataId为nacos-config,文件后缀为Properties,设置内容user.name=jack:

在application.yml同目录下创建bootstrap.yml文件,并配置Nacos服务地址以及namespace(没有就不需要配置):
spring:
application:
name: nacos-config-client
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848
namespace: 68468122-8955-45ee-a5b7-3d87972325b1
dataId对应步骤2里面的dataId,有两种配置方式,一种是官方自动构建dataId ,另一种是指定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 来配置。目前只支持 properties 和 yaml 类型。比如项目名称为nacos-config-client,当前环境为test,格式文件为properties,那就需要新建一个dataId为nacos-config-client.properties配置。
在NacosConfigProperties类里面name字段就是配置dataId:
public class NacosConfigProperties {
/**
* nacos config dataId name.
*/
private String name;
//省略其他配置
}
在bootstrap.yml添加spring.cloud.nacos.config.name就可以设置dataId。
通过@Value就能获取配置文件的数据:
@Component
@RefreshScope
public class TestConfig {
@Value(value = "${user.name:null}")
private String test;
public String getTest(){
return test;
}
要实现配置的自动更新,需要添加Spring Cloud原生注解 @RefreshScope。controller直接调用即可:
@RestController
public class TestController {
@Autowired
private TestConfig testConfig;
@GetMapping("/config")
public String testConfig(){
String config = testConfig.getTest();
return config;
}
}
如果想通过@NacosValues注解获取数据,需要引入nacos-config-spring-boot-starter依赖:
com.alibaba.boot
nacos-config-spring-boot-starter
0.2.7
nacos-config配置首先添加spring-cloud-starter-alibaba-nacos-config依赖。bootstrap.properties添加nacos server地址和namespacedataId有两种方式
spring.cloud.nacos.config.name${prefix}-${spring.profiles.active}.${file-extension}规则配置,其中prefix为项目名称,spring.profiles.active为项目运行环境,file-extension配置内容的数据格式。@Value(value = "${user.name:null}")设置在字段上就能获取到属性,要实现自动更新配置需要添加@RefreshScope注解。