搭建java项目
-
项目结构
-
在nacos-configcenter的pom.xml中添加依赖
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>
-
编写bootstrap.yml
spring: application: name: nacos-configcenter cloud: nacos: config: server-addr: 127.0.0.1:8848 username: nacos password: nacos discovery: server-addr: 127.0.0.1:8848 username: nacos password: nacos inetutils: preferred-networks: 192.168.31 server: port: 8083
-
编写测试类
@Component @RefreshScope// 标志当前配置如果在配置中心被修改后,服务里面的需要被更新 public class RefreshConfig { @Value("${key}") private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } } @Component public class NotRefreshConfig { @Value("${value}") private String value; public String getValue() { return value; } public void setValue(String value) { this.value = value; } }
-
测试controller
@RestController public class ConfigTestController { @Autowired private RefreshConfig refreshConfig; @Autowired private NotRefreshConfig notRefreshConfig; @GetMapping("getConfig") public String getConfig() { return "key:" + refreshConfig.getKey() + "\tvalue:" + notRefreshConfig.getValue(); } }
配置nacos
-
登录nacos,创建一个配置
-
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 Boot文档。 注意:当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}
file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 properties 和 yaml 类型。所以当前项目需要配置的dataId是nacos-configcenter.properties
运行结果
- 直接访问接口http://127.0.0.1:8083/getConfig
- 修改nacos中配置的key和value2个配置项
- 再次访问接口http://127.0.0.1:8083/getConfig
key 被刷新了 value没有被刷新,这里验证了上面@RefreshScope的作用
注意
-
在springcloud中 bootstrap,application配置文件是有加载先后顺序的
bootstrap 先于 application 加载,所以系统级别的配置文件我们会在bootstrap中定义,应用级别的我们会在application中定义
当使用bootstrap的时候能够正确加载配置信息
当使用application的时候不能正确加载配置信息