• Nacos配置管理


    Nacos配置管理

    统一配置管理

    在Nacos中添加配置文件*(名称-环境.文件格式)*

    测试:

    配置内容

      pattern:
        dateformat: MM-dd HH:mm:ss:SSS
    
    • 1
    • 2

    image-20220813143429457

    1.引入Nacos的配置管理客户端依赖

    
    
        com.alibaba.cloud
        spring-cloud-starter-alibaba-nacos-config
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2.在userservice中的resource目录添加一个bootstrap.yml,这个文件是引导文件,优先级高

    spring:
      application:
        name: userservice
    
      profiles:
        active: dev  #环境
    
      cloud:
        nacos:
          server-addr: localhost:8848  #nacos地址
          config:
            file-extension: yaml  #文件后缀名
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3.测试,获取配置文件中的日期格式

    @Value("${pattern.dateformat}")
    private String dataformate;
    
    @GetMapping("now")
    public String now(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dataformate));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    image-20220813145434629

    配置热更新

    Nacos中的配置文件变更后,微服务无需重启就能感知。

    方式一:

    在@Value注入的变量所在类上添加注解@RefreshScope

    image-20220813145827397

    在这里插入图片描述

    方式二:使用@ConfigurationProperties注解

    @Component
    @Data
    @ConfigurationProperties(prefix = "pattern")
    public class PatternProperties {
        private String dateformat;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    @Autowired
    private PatternProperties patternProperties;
    
    @GetMapping("now")
    public String now(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(patternProperties.getDateformat()));
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    多环境配置共享

    无论环境如何变化,userservice.yaml一定会加载

    image-20220813151256269

    测试:

    在ParrernProperties类中

    @Component
    @Data
    @ConfigurationProperties(prefix = "pattern")
    public class PatternProperties {
        private String dateformat;
    
        private String envSharedValue;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    展示到页面上

    @GetMapping("prop")
    public String prop(){
        return patternProperties.getEnvSharedValue();
    }
    
    • 1
    • 2
    • 3
    • 4

    image-20220813151247921

    多种配置的优先级

    服务名-profiole.yaml>服务名称.yaml>本地配置

  • 相关阅读:
    vim 配置C/C++单文件无参数编译运行
    powderdesigner 关于mysql生成pdm和java的方法
    MMLAB系列:MMCLS基本操作
    LNMP编译安装
    GO-日志分析
    暑假加餐|有钱人和你想的不一样(第17天)+高比例风电电力系统储能运行及配置分析(Matlab代码实现)
    我用ChatGPT做直播技术选型,卷死了同事
    编程学:关于同类词的等长拼写问题
    webSocket的实现
    【网络篇】如何在服务器之间建立互信
  • 原文地址:https://blog.csdn.net/qq_57907966/article/details/126361254