• IDEA04:动态加载配置文件


    写在前面

    • 动态加载配置文件就是在程序运行的过程中实时监控配置文件的状态,在发生变化时重新加载,而无需停止程序。

    • 这里主要是介绍如何在Java环境中实现动态加载配置文件。

    • 主要参考了博文:java动态加载配置文件

    一、引入依赖包

    • commons-io主要是用于实现文件更改的监控。
    
    <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.11.0version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    二、配置配置文件

    三、程序demo

    • JSON文件的解析用的是fastjson库;
    • load()函数用于加载配置文件;
    • 监听程序用了线程,这样可以避免阻塞主线程;
    • 记录到的配置项使用HashMap来保存,方便使用;
    • getConfig()函数来返回读到内存中的配置;
    • 注意load()getConfig()均对同一个变量进行操作,需要加锁。

    程序如下:

    import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.io.FileUtils;
    import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
    import org.apache.commons.io.monitor.FileAlterationMonitor;
    import org.apache.commons.io.monitor.FileAlterationObserver;
    
    @Slf4j
    public class DynamicConfig implements Runnable {
    
        // 指定文件名及相关路径
        private String filename = "config.properties";
    
        private String rootDir = System.getProperty("root.dir", System.getProperty("user.dir"));
    
        private String filePath = rootDir + File.separator + filename;
    
        // 用HashMap存放配置
        private HashMap<Integer, String> config = new HashMap<>();;
    
        public DynamicConfig() {
            // 使用默认配置文件路径
        }
    
        public DynamicConfig(String filePath) {
            // 使用传入的配置文件路径覆盖默认路径
            this.filePath = filePath;
        }
    
        // 返回config,已加锁
        public synchronized HashMap<Integer, String> getConfig() {
            return config;
        }
    
        // 加载配置文件更新config,已加锁
        private synchronized void load() {
            File file = new File(filePath);
            if (!file.exists()) {
                log.warn("File is not exist. file: {}", file.getAbsolutePath());
                return;
            }
            File configFile = new File(filePath);
            try {
                // 清空HashMap
                config.clear();
    
                // 加载配置文件
                String configContent = FileUtils.readFileToString(configFile, "UTF-8");
                JSONObject configJson = JSON.parseObject(configContent);
    
                log.info("Load config, file: {}", file.getAbsolutePath());
                // 打印当前加载的配置
                JSONArray  patterns = configJson.getJSONArray("patterns");
                for(int i=0;i<patterns.size();i++)
                {
                    JSONObject pattern = patterns.getJSONObject(i);
                    // 解析配置数组内容
                    int pattern_id = pattern.getInteger("pattern_id");
                    String method = pattern.getString("method");
                    System.out.println(String.valueOf(pattern_id) + ":" + method);
    
                    // 记录到HashMap
                    config.put(pattern_id, method);
                }
            } catch (IOException e) {
                log.error("Load config error.", e);
            }
        }
    
        @Override
        public void run() {
            // 文件变动监听,监听的是这个目录
            FileAlterationObserver observer = new FileAlterationObserver(rootDir);
            observer.addListener(new FileAlterationListenerAdaptor() {
                @Override
                public void onFileCreate(File file) {
                    // 当指定的文件创建的时候
                    if (filename.equals(file.getName())) {
                        log.info("Config file create. file: {}", file.getAbsolutePath());
                        load();
                    }
                }
    
                @Override
                public void onFileChange(File file) {
                    // 当指定的文件修改的时候
                    if (filename.equals(file.getName())) {
                        log.info("Config file change. file: {}", file.getAbsolutePath());
                        load();
                    }
                }
    
                @Override
                public void onFileDelete(File file) {
                    // 当指定的文件删除
                    if (filename.equals(file.getName())) {
                        log.info("Config file delete file: {}", file.getAbsolutePath());
                    }
                }
            });
            observer.checkAndNotify();
            FileAlterationMonitor monitor = new FileAlterationMonitor();
            monitor.addObserver(observer);
            try {
                monitor.start();
                log.info("Start file change monitor. Path: {}", rootDir);
            } catch (Exception e) {
                log.error("Init file change error.", e);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117

    四、一些报错

    1. SLF4J: No SLF4J providers were found.

    • 场景
    • 程序一开始运行时,在控制台输出报错。
    • 程序能够正常运行,但无法输出日志。
    • 原因
    • Slf4j可以看作是Log4j的标准接口,它本身不包含实现。
    • 因此Maven如果配置不当,很容易出现No SLF4J providers were found的错误,这表明程序无法生成可用的Slf4j实例。
    • 解决方法
    • 参考博客:SLF4J 报错解决:No SLF4J providers were found
    • Maven依赖需要配置两个包,如果是从https://mvnrepository.com/直接拷贝的话,需要把slf4j-simpletest删掉,否则在编译的时候不起作用:
    
    <dependency>
    	<groupId>org.slf4jgroupId>
    	<artifactId>slf4j-apiartifactId>
    	<version>2.0.0-alpha5version>
    dependency>
    
    <dependency>
    	<groupId>org.slf4jgroupId>
    	<artifactId>slf4j-simpleartifactId>
    	<version>2.0.0-alpha5version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 关于的更多说明可以参考博文:Maven中的scope总结
    • 另外,实现@Slf4j注解可以避免每次写日志时都需要使用日志对象,直接用log即可。
    • @Slf4j注解需要Lombok插件,Maven配置如下:
    
    <dependency>
    	<groupId>org.projectlombokgroupId>
    	<artifactId>lombokartifactId>
    	<version>1.18.24version>
    	<scope>providedscope>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    全面采集商品数据的电商API接口对接【支持5大主流电商平台】
    基于寄生捕食算法优化概率神经网络PNN的分类预测 - 附代码
    compact unwind compressed function offset doesn‘t fit in 24 bits
    【python学习】基础篇-常用模块-re模块:正则表达式高效操作字符串
    什么是UI自动化测试工具?
    JWT主动校验Token是否过期
    ADG dataguard ALL_LOGFILES,ALL_ROLES
    R语言基于指定规则、条件删除列表中的元素:使用purrr包的discard函数移除模型列表中的R方指标低于指定阈值的模型(列表元素为lm模型、筛选条件为R方)
    HCIA 动态路由与OSPF原理
    Stream流的常用方法
  • 原文地址:https://blog.csdn.net/weixin_43992162/article/details/126178790