Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to modify yml configuration file dynamically by SpringBoot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the relevant knowledge of "how SpringBoot dynamically modifies the yml configuration file". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Preface

Record how SpringBoot does not need to restart the service after modifying the yml configuration file (effective after packaging). The results are as follows:

Specific implementation code

Pom.xml

Org.springframework.boot spring-boot-starter-web org.projectlombok lombok

Application.yml

# Port number server: port: 31091spring: 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 container initialization completes some other initialization operations * @ date Mar 24,2022 * @ version 1.0 * / @ Slf4j@Componentpublic 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 ("load profile application.yml exception") } / / TODO enables regular refresh of configuration file contents in memory log.info ("refresh config file start"); executorService.scheduleAtFixedRate (InitializationConfig::updateConfVal, 0,10, TimeUnit.SECONDS); log.info ("refresh config file end") } / * Update profile value * / 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 ("Real-time configuration mail updates:" + instance.getDynamicMail ());}} catch (Exception e) {log.error ("Update profile value exception:", e);}

DynamicMailConfig.java

/ * * @ Description dynamic mailbox singleton * @ 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 dynamic manipulation yml configuration file tool class * [you need to put the config configuration folder and the project jar package in the same level directory, so that after modifying the configuration file under config, jvm can get the new configuration in time] * @ 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 if there is no config folder, look for in = YmlUtil.class.getClassLoader () .getResourceAsStream (fileName) from the project's resources directory } 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; iTunes +) {Object value = ymlInfo.get (keys [I]) If (I < keys.length-1) {ymlInfo = (Map) value;} else if (value = = null) {throw new Exception ("key does not exist");} else {return value;}} return null;}} Test

TestController.java

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

The packaged configuration file is placed in the config directory at the same level as jar.

This is the end of the content of "how SpringBoot dynamically modifies the yml configuration file". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report