码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-04 13:26:52      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:rtrim(   bug   extend   slf4j   demo   init   关于   property   readline   

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

至于,如果使用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.

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

标签:rtrim(   bug   extend   slf4j   demo   init   关于   property   readline   

原文地址:https://www.cnblogs.com/lichmama/p/9262510.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!