首頁 > 軟體

SpringBoot動態修改yml組態檔的方法詳解

2022-03-30 16:00:21

前言

記錄下SpringBoot修改yml組態檔後無需重啟服務的方式(打包後生效),效果如下:

具體實現

實現程式碼

pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>

application.yml

#埠號
server:
  port: 31091
spring:
  profiles:
    active: dev

application-dev.yml

coisini:
    mail: maggieq8324@gmail.com

InitializationConfig.java

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * @Description spring容器初始化完成後進行一些其他初始化操作
 * @date Mar 24, 2022
 * @version 1.0
 */
@Slf4j
@Component
public class InitializationConfig implements ApplicationRunner {
    private static ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    private static String profile;
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        scheduleUpdateConf();
    }
    private void scheduleUpdateConf() {
        try {
            Map lhm = YmlUtil.loadYaml("application.yml");
            profile = (String) YmlUtil.getValByKey(lhm, "spring.profiles.active");
        } catch (Exception e) {
            log.error("載入組態檔application.yml異常");
        }
        // TODO 開啟定時重新整理記憶體中組態檔內容
        log.info("refresh config file start");
        executorService.scheduleAtFixedRate(InitializationConfig::updateConfVal, 0, 10, TimeUnit.SECONDS);
        log.info("refresh config file end");
    }
    /**
     * 更新組態檔值
     */
    private static void updateConfVal(){
        try{
            Map lhm = YmlUtil.loadYaml("application-" + profile + ".yml");
            String mail = YmlUtil.getValByKey(lhm,"coisini.mail").toString();
            DynamicMailConfig instance = DynamicMailConfig.getInstance();
            if (!instance.getDynamicMail().equals(mail)) {
                instance.setDynamicMail(mail);
                log.info("實時設定mail更新:" + instance.getDynamicMail());
            }
        } catch (Exception e){
            log.error("更新組態檔值異常: ", e);
        }
    }
}

DynamicMailConfig.java

/**
 * @Description 動態郵箱單例
 * @date Mar 24, 2022
 * @version 1.0
 */
public class DynamicMailConfig {
    private static String mail;
    private final static DynamicMailConfig dynamic;
    static {
        dynamic = new DynamicMailConfig();
    }
    private DynamicMailConfig() {
        mail = "";
    }
    public static DynamicMailConfig getInstance() {
        return dynamic;
    }
    public String getDynamicMail() {
        return mail;
    }
    public void setDynamicMail(String mail) {
        this.mail = mail;
    }
}

YmlUtil.java

import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
/**
 * @Description 動態操作yml組態檔工具類
 *  【需要將config組態檔夾和專案jar包放在同級別目錄下,這樣修改config下的組態檔後,jvm才能及時得獲取新的設定】
 * @date Mar 24, 2022
 * @version 1.0
 */
public class YmlUtil {
    public static LinkedHashMap loadYaml(String fileName) throws Exception{
        String path = System.getProperty("user.dir");
        File file = new File(path + "/config/" + fileName);
        InputStream in;
        if (file.exists()) {
            in = new FileInputStream(path + "/config/" + fileName);
        } else {
            // TODO 如果沒有config資料夾,則從專案的resources目錄下找
            in = YmlUtil.class.getClassLoader().getResourceAsStream(fileName);
        }
        LinkedHashMap lhm = new Yaml().loadAs(in, LinkedHashMap.class);
        return lhm;
    }
    public static Object getValByKey(Map lhm, String key) throws Exception{
        String[] keys = key.split("[.]");
        Map ymlInfo = lhm;
        for (int i = 0; i < keys.length; i++) {
            Object value = ymlInfo.get(keys[i]);
            if (i < keys.length - 1) {
                ymlInfo = (Map) value;
            } else if (value == null) {
                throw new Exception("key不存在");
            } else {
                return value;
            }
        }
        return null;
    }
}

測試 

TestController.java

@Slf4j
@RestController
public class TestController {
    @GetMapping("/getDynamicMail")
    public String getDynamicMail() {
        String dynamicMail = DynamicMailConfig.getInstance().getDynamicMail();
        log.info("getDynamicMail: " + dynamicMail);
        return dynamicMail;
    }
}

打包後組態檔放在與jar同級的config目錄下

原始碼

GitHubhttps://github.com/Maggieq8324/java-learn-demo/tree/master/springboot-dynamic-yml

Giteehttps://gitee.com/maggieq8324/java-learn-demo/tree/master/springboot-dynamic-yml

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!


IT145.com E-mail:sddin#qq.com