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

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

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

 

配置样例:

# settings for admin
admin.name=lichmama
admin.notify=true
admin.email=lichmama@cnblogs.com
admin.threshold=10

 

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 {
    private static final int INITIAL_CAPACITY = 1000;

    @Slf4j
    private static class ConfigMap extends ConcurrentHashMap<String, Object> {
        public ConfigMap(List<String> configLocations) {
            super(INITIAL_CAPACITY);
            initConfigMap(configLocations);
        }

        private void initConfigMap(List<String> configLocations) {
            if (configLocations == null || configLocations.size() == 0) {
                log.debug("initConfigMap finished, configLocations is null");
                return;
            }
            for (String configFile : configLocations)
                loadConfigFile(configFile);
        }

        /**
         * support 3 protocols: http|ftp|file
         * 
         * @param configFile
         * @throws IOException
         */
        private void loadConfigFile(String configFile) {
            log.debug("loading configFile: {}", configFile);
            if (!configFile.matches("^(?:http|ftp|file)://.*?$")) {
                if (!configFile.startsWith("/"))
                    configFile = "/" + configFile;
                configFile = "file://" + configFile;
            }
            try (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);
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new IllegalArgumentException(
                        "unexpected exception occurs when load configFile [" + configFile + "]");
            }
        }
    }

    private ConfigUtil() {
    }

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

    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 boolean exists(String key) {
        return configMap.containsKey(key);
    }

    public static Object getConfig(String key, Object preset) {
        if (!exists(key))
            return preset;
        return getConfig(key);
    }

    public static String getString(String key) {
        Object object = getConfig(key);
        if (object == null)
            return null;
        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>D:/sys/settings.conf</value>
        </list>
    </property>
</bean>

 

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

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

    @RequestMapping("/set")
    @ResponseBody
    public ActionMessage setConfig(@RequestParam String key, @RequestParam String value) {
        if (StringUtil.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.

posted @ 2018-07-04 11:36  lichmama  阅读(300)  评论(0编辑  收藏  举报