1.Nacos动态配置
在系统开发过程中,开发者通常会将一些需要变更的参数、变量等从代码中分离出来独立管理,以独立的配置文件的形式存在。目的是让静态的系统工件或者交付物(如 WAR,JAR 包等)更好地和实际的物理运行环境进行适配。配置管理一般包含在系统部署的过程中,由系统管理员或者运维人员完成。配置变更是调整系统运行时的行为的有效手段。
2.如何使用
在项目中新增bootstrap.yml文件,配置信息写在该文件里(问题:如放在application.yml会导致项目启动报找不到配置属性错误,原因:application.yml与bootstrap.yml加载顺序优先级问题。)
bootstrap.yml(bootstrap.properties)用来程序引导时执行,应用于更加早期配置信息读取,如可以使用来配置application.yml中使用到参数等
application.yml(application.properties) 应用程序特有配置信息,可以用来配置后续各个模块中需使用的公共参数等。
加载顺序:bootstrap.yml > application.yml > application-dev(prod).yml > …
在bootstrap.yml中新增application.name和nacos的config信息。
spring:application:name: service-providercloud:nacos:config:server-addr: 127.0.0.1:8848file-extension: propertiesgroup: DEFAULT_GROUP
然后修改TestController的代码:
package com.zym.controller;import org.springframework.beans.factory.annotation.Value;import org.springframework.cloud.context.config.annotation.RefreshScope;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;@RestController@RefreshScope//动态刷新配置public class TestController {@Value("${userinfo.realname}")private String realname;@RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)public String echo(@PathVariable String string) {return "Hello Nacos Discovery " + string;}@RequestMapping(value = "test",method = RequestMethod.GET)public String test(){return "success";}@RequestMapping(value = "/getUserName",method = RequestMethod.GET)public String getUserName(){return realname;}}
我们在Nacos新增配置文件:

这里需要注意的点是Data ID
在 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类型。
然后我们调用接口:http://localhost:8070/getUserName
然后我们修改配置文件,将张三改成李四重新调接口:
