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


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

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

  • 相关阅读:
    【MYSQL】某些有用的sql【持续更新中】
    【LDAP】什么时候需要使用LDAP?
    【LDAP】 objectClass 分类
    MySQL的锁机制
    spring的事务传播级别及场景
    @NotEmpty,@NotNull和@NotBlank的区别
    mysql的字段为bit时,插入数据报Data too long
    activeMQ启动报--找不到或无法加载主类
    【ListViewJson】【com.demo.app】【AppException】源码分析及其在工程中作用
    【ListViewJson】【com.demo.app】【AppConfig】源码分析及其在工程中作用
  • 原文地址:https://www.cnblogs.com/lichmama/p/9262510.html
Copyright © 2020-2023  润新知