lsekfe 发表于 2023-2-21 10:36:15

配置管理之多环境共享---Nacos

微服务启动时会从nacos读取多个配置文件:
  1、-.yaml 例如:userservice-dev.yaml
  【服务名】-【环境】.yaml
  2、 .yaml【服务名】.yaml 例如:userservice.yaml
  无论profile(环境)如何变化,.yaml 这个文件一定会被加载、一定会被读取,因此多环境共享的配置可以写入这个文件。
http://www.51testing.com/attachments/2023/02/15326880_202302201327361G6OV.pnghttp://www.51testing.com/attachments/2023/02/15326880_202302201327391FgAP.pnghttp://www.51testing.com/attachments/2023/02/15326880_202302201327421wANl.png
  读取Nacos配置的userservice.yaml文件
  前面学过读取Nacos配置文件方式二,通过@ConfigurationProperties注解读取;
  @Component
  @Data
  @ConfigurationProperties(prefix = "pattern")
  public class PatternProperties {
      private String dateformat;
      private String envSharedvalue;
  }
  @RestController
  @RequestMapping("user")
  public class UserController {

      @Autowired
      private PatternProperties properties;

      @GetMapping("/prop")
      public PatternProperties properties(){
        return properties;
      }
  }


   微服务是如何知道要读取Nacos中配置的userservice.yaml文件你呢?
   通过之前的学习可以知道,bootstrap.yml文件是会优先被Nacos读取的,如图所示,我们在bootstrap.yml里面配置了 Nacos地址、微服务名、文件后缀名,由这三部分即可组成 userservice.yaml 文件配置名,也就是你在Nacos配置中心配置的名字,Nacos就是通过这种方式找到需要读取的配置文件的。
  根据图片配置,可以得知 userservice-dev.yaml 配置文件也会被读取到,但是 userservice.yaml配置文件是一定会被读取的。
http://www.51testing.com/attachments/2023/02/15326880_202302201327451Lv3z.png
  多环境配置读取测试
   端口号为8081的userservice微服务激活dev环境,端口号8082的激活test环境;分别启动这两个微服务,那么激活环境为dev端口号为8081的服务不仅可以读取到日期格式属性dateformat、也可以读取到envSharedvalue属性,而端口号8082由于激活的是测试环境test,那么只能读取共享配置userservice.yaml里面的 envSharedvalue 属性。
http://www.51testing.com/attachments/2023/02/15326880_202302201327481R8ff.pnghttp://www.51testing.com/attachments/2023/02/15326880_202302201327501nqZX.png
   测试结果:服务8082只能读取到共享属性envSharedvalue的值。
http://www.51testing.com/attachments/2023/02/15326880_202302201327531vuhh.png
   端口号8081的服务由于激活的是dev环境,所以可以读取到 userservice-dev.yaml配置文件的配置,又由于 userservice.yaml 共享文件的配置是一定可以被服务读取到的,那么共享文件中的envSharedvalue属性也会被读取;两个属性都有值。
http://www.51testing.com/attachments/2023/02/15326880_202302201327561jVzc.png
  多种配置的优先级
   同一种属性名的值在本地配置文件中配置(也就是application.yml),在Nacos中也配置,在Nacos中配置多环境共享配置 userservice.yaml,还有非多环境共享配置 userservice-dev.yaml,那么获取这个属性值的优先级是什么呢?以哪个配置文件中的值为准呢?
  优先级如下:
  服务名-profile.yaml > 服务名称.yaml > 本地配置;
  userservice-dev.yaml > 多环境共享配置 userservice.yaml > application.yml
  总结
http://www.51testing.com/attachments/2023/02/15326880_2023022013280015EOu.png

页: [1]
查看完整版本: 配置管理之多环境共享---Nacos