Spring boot实现更改配置文件后自动更新配置

一、原理说明

    业务目标是实现当配置文件变更后能自动生效而不需要重启程序。实现依赖spring cloud的ContextRefresher对象和文件监听器

二、实现思路

  1、使用apache的commons-io的文件监听器来监控配置文件是否变动,当配置文件变动后调用contextRefresher.refresh()方法使Spring重新加载配置信息

    2、在需要支持配置变化的使用类添加@RefreshScope注解用来表示该类下的@Value需要更新配置信息

    3、spring boot的scheduled会因为refresh()方法而失效,所以需要调度类继承ApplicationListener接口并在刷新事件变更后调用一次调度方法即可

三、实现方法

    1、添加commons-io依赖

    2、编写一个文件监听启动类继承CommandLineRunner接口在run()方法中启动文件监听器

       FileAlterationMonitor monitor = new FileAlterationMonitor(1000);

       FileAlterationObserver observer = new FileAlterationObserver(file);

        observer.addListener(new ConfigFileListener());

        monitor .addObserver(observer);

        monitor.start();

    3、编写一个ConfigFileListener类继承FileAlterationListenerAdaptor,在onFileChange()方法中调用

contextRefresher.refresh()即可

    4、优化代码发所有的配置类尽量走配置类,在配置类添加@RefreshScope注解

    5、在调度类添加ApplicationListener接口在onApplicationEvent()实现方法中调用一次调度类

        this.myScheduled();

上一篇:UVM(六):验证环境的组成:UVM组件家族——uvm_component


下一篇:MySQL基础指令