支持读取远程配置文件的配置类

Posted lichmama

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了支持读取远程配置文件的配置类相关的知识,希望对你有一定的参考价值。

可将配置文件与工程文件分离,并减少一些分布式工程中关于配置的重复劳动。

至于,如果使用redis是不是一个更好的选择这就仁者见仁了。

 

ConfigUtil:

技术分享图片
package com.lichmama.demo.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.UrlResource;

import lombok.extern.slf4j.Slf4j;

public class ConfigUtil implements InitializingBean {

    @Slf4j
    private static class ConfigMap extends ConcurrentHashMap<String, Object> {
        public ConfigMap(List<String> configLocations) {
            // set the initialCapacity to 1000
            super(1000);
            initConfigMap(configLocations);
        }

        private void initConfigMap(List<String> configLocations) {
            if (configLocations == null || configLocations.size() == 0)
                throw new IllegalArgumentException(
                        "cannot initialize the [ConfigUtil], because property "configLocations" is null");
            for (String configFile : configLocations) {
                try {
                    loadConfigFile(configFile);
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                    throw new IllegalArgumentException(
                            "unexpected exception occurs when load configFile [" + configFile + "]");
                }
            }
        }

        /**
         * support 3 protocols: http|ftp|file
         * 
         * @param configFile
         * @throws IOException
         */
        private void loadConfigFile(String configFile) throws IOException {
            log.debug("loading configFile: " + configFile);
            if (!configFile.matches("^(?:http|ftp)://.*?$"))
                configFile = "file:///" + configFile;
            InputStream is = new UrlResource(configFile).getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line;
            while ((line = br.readLine()) != null) {
                if (!line.matches("^[A-Za-z0-9._]+\s*=.*?$"))
                    continue;
                String[] keyAndValue = line.split("=", 2);
                String key = keyAndValue[0].trim();
                String value = keyAndValue[1];
                if (StringUtil.isNotEmpty(value)) {
                    value = StringUtil.ltrim(value);
                    value = StringUtil.rtrim(value);
                }
                put(key, value);
            }
            br.close();
        }
    }

    private ConfigUtil() {
    }

    private List<String> configLocations;
    private static ConfigMap configMap;

    public List<String> getConfigLocations() {
        return configLocations;
    }

    public void setConfigLocations(List<String> configLocations) {
        this.configLocations = configLocations;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        configMap = new ConfigMap(configLocations);
    }

    public static Object getConfig(String key) {
        return configMap.get(key);
    }

    public static void setConfig(String key, Object value) {
        configMap.put(key, value);
    }

    public static String getString(String key) {
        Object object = getConfig(key);
        if (object == null)
            return "";
        return String.valueOf(object);
    }

    public static int getInt(String key) {
        return Integer.parseInt(getString(key));
    }

    public static boolean getBoolean(String key) {
        return Boolean.parseBoolean(getString(key));
    }
}
View Code

 

在spring中的配置:

<bean class="com.lichmama.demo.common.util.ConfigUtil">
    <property name="configLocations">
        <list>
            <!--<value>http://192.168.1.101/sys/settings.conf</value>-->
            <value>file:///D:/sys/settings.conf</value>
        </list>
    </property>
</bean>

 

增加动态修改配置的功能:

@Controller
@RequestMapping("/config")
@Slf4j
public class TestAction {

    @RequestMapping("/set")
    @ResponseBody
    public ActionMessage setConfig(@RequestParam String key, @RequestParam String value) {
        if (StringUtils.isEmpty(value))
            return ActionStatus.error("key is null");
        log.debug("key: {}, value: {}", key, value);
        ConfigUtil.setConfig(key, value);
        return ActionStatus.success();
    }

    @RequestMapping("/get")
    @ResponseBody
    public String getConfig(@RequestParam String key) {
        String value = ConfigUtil.getString(key);
        log.debug("key: {}, value: {}", key, value);
        return value;
    }
}

 

that‘s it.

以上是关于支持读取远程配置文件的配置类的主要内容,如果未能解决你的问题,请参考以下文章

java 读取配置文件

Linux shell (ssh批量配置免秘)读取配置文件,进行远程操作

使用Viper读取Nacos配置(开源)

Viper的简单实用

golang 配置文件解析神器--viper

Viper--方便好用的Golang 配置库