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信息。

  1. spring:
  2. application:
  3. name: service-provider
  4. cloud:
  5. nacos:
  6. config:
  7. server-addr: 127.0.0.1:8848
  8. file-extension: properties
  9. group: DEFAULT_GROUP

然后修改TestController的代码:

  1. package com.zym.controller;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.cloud.context.config.annotation.RefreshScope;
  4. import org.springframework.web.bind.annotation.PathVariable;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.bind.annotation.RestController;
  8. @RestController
  9. @RefreshScope//动态刷新配置
  10. public class TestController {
  11. @Value("${userinfo.realname}")
  12. private String realname;
  13. @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET)
  14. public String echo(@PathVariable String string) {
  15. return "Hello Nacos Discovery " + string;
  16. }
  17. @RequestMapping(value = "test",method = RequestMethod.GET)
  18. public String test(){
  19. return "success";
  20. }
  21. @RequestMapping(value = "/getUserName",method = RequestMethod.GET)
  22. public String getUserName(){
  23. return realname;
  24. }
  25. }

我们在Nacos新增配置文件:
2.png
3.png
这里需要注意的点是Data ID

在 Nacos Spring Cloud 中,dataId 的完整格式如下:

  1. ${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 来配置。目前只支持 propertiesyaml 类型。

然后我们调用接口:http://localhost:8070/getUserName
1.png
然后我们修改配置文件,将张三改成李四重新调接口:
4.png