• 【非官方方式】获取Disconf动态更新的配置文件的值


    disconf可以配置reload,当更改配置时自动刷新classpath下的配置文件。然而获取最新的值官方说明是加@DisconfFileItem注解放在属性的方法上,底层通过拦截器获取的。

    但是每个属性都要定义一个属性,其实是一件很繁琐的事情。

    所以,以下提供一种非官方实时获取最新值的方式。

     1 public class PropertiesUtils {
     2     private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
     3     private static final String charset = "UTF-8";
     4     private static final Properties sysProp = new Properties();
     5     private static long lastModify = 0L;
     6     private static File system;
     7     private PropertiesUtils() {
     8         throw new IllegalAccessError("Utility class");
     9     }
    10     static {
    11         try {
    12             system = new ClassPathResource("system.properties").getFile();
    13             load(system.lastModified());
    14         } catch (Exception e) {
    15             logger.error("properties file load error",e);
    16             throw new RuntimeException(e);
    17         }
    18     }
    19 
    20     private static void load(long updateTime) {
    21         try {
    22             //注意清空,否则没有新值,会使用旧值
    23             sysProp.clear();
    24             //获取属性
    25             sysProp.load(new InputStreamReader(new FileInputStream(system), charset));
    26             //获取文件修改时间
    27             lastModify = updateTime;
    28         } catch (IOException e) {
    29             throw new RuntimeException(e);
    30         }
    31     }
    32 
    33     
    34     /**获取属性配置值
    35      * @param name 名称
    36      * @return
    37      */
    38     public static String getProp(String name) {
    39         long modify = system.lastModified();
    40         if (modify > lastModify) load(modify);
    41         return  sysProp.getProperty(name);
    42     }
    43 }

    通过判断文件是否更改,从而得到最新配置的值。

    这样获取配置就不需要每个都定义一个属性了。

  • 相关阅读:
    Linux 多线程编程 实例 1
    面试题-链表反转c实现
    information_schema.TABLES
    mongodb遇到的错误
    MySQL优化的奇技淫巧之STRAIGHT_JOIN
    mongodb安装
    XtraBackup安装
    提高mysql千万级大数据SQL查询优化30条经验(Mysql索引优化注意)
    我用 TypeScript 语言的七个月
    Grunt之添加文件监视:Grunt-watch (已备份)
  • 原文地址:https://www.cnblogs.com/jay763190097/p/11760895.html
Copyright © 2020-2023  润新知