Spring boot 動態更新外部配置

在網上查找一下,好像沒有現成的解決方法,在此記錄一下,供你們參考實現。ide

     前提Spring boot 工程,使用的是yml 文件格式(其餘格式同樣的,換一下加載類),整體解決思路,啓動定時器,定時檢測外部文件是否有修改。若是文件被修改,獲取配置文件內容後進行業務處理。測試

一. 定時器get

public void init() {

    scheduled = Executors.newScheduledThreadPool(1);
    scheduled.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            refresh();
        }

    }, 1, 10, TimeUnit.SECONDS); //測試時間比較短,根據實際需求修改,如5分鐘
}

二. 刷新查看it

public void refresh() {

    try {

        if (filePath.equalsIgnoreCase("NONE")) {
            scheduled.shutdown();
        }

        FileSystemResource fileSystemResource = new FileSystemResource(filePath);
        if (lastModified == fileSystemResource.getFile().lastModified()) return;  // 沒有修改,直接返回。

        YamlPropertySourceLoader yamLoader = new YamlPropertySourceLoader();
        PropertySource<LinkedHashMap> yamProp = (PropertySource<LinkedHashMap>) yamLoader.load("YamFileName", fileSystemResource, null);

        LinkedHashMap linkedHashMap = yamProp.getSource();
        System.out.println("props FileInputStream size=" + linkedHashMap.size());

        lastModified = fileSystemResource.getFile().lastModified();

    } catch (Exception e) {
        e.printStackTrace();
    }

3,類變量io

long lastModified = 0;

ScheduledExecutorService scheduled;

@Value("${***.file.path:NONE}")
String filePath;

獲取到數據後,直接操做Environment ,仍是保存本地類變量均可以操做,ast

PropertySource<LinkedHashMap>  ,根據實際格式處理,PropertySource<?>變量

相關文章
相關標籤/搜索