美文网首页
项目使用配置中心简化处理

项目使用配置中心简化处理

作者: 后来丶_a24d | 来源:发表于2020-04-21 16:11 被阅读0次

目录


需求

  • 配置中心添加key时,只需要修改一个地方就可以调用,不需要额外处理

Test类

  • 配置中心线上添加了一个key,这里只需要enum添加就可以调用
  public static void main(String[] args) {
        System.out.println(ConfigProperties.newInstance().get(ConfigPropertyEnum.TEST));
    }

enum类

  • 线上新增配置时,只需要改动这一处即可
public interface IConfigPropertyEnum {
    String key();
    String defaultValue();
}

public enum ConfigPropertyEnum implements IConfigPropertyEnum{
    TEST("testKey", "testValue")
    ;

    private String key;
    private String defaultValue;

    ConfigPropertyEnum(String key, String defaultValue) {
        this.key = key;
        this.defaultValue = defaultValue;
    }

    @Override
    public String key() {
        return this.key;
    }

    @Override
    public String defaultValue() {
        return this.defaultValue;
    }
}

从配置中心获取数据类

public class ConfigProperties {

    private static class ConfigPropertiesHolder {
        public static ConfigProperties INSTANCE = new ConfigProperties();
    }

    // 非线程安全,由于配置中心的修改是portal人为修改,正常没有并发
    private Map<String, String> configs;

    private ConfigProperties(){
        // 获取配置中心客户端的properties,这里用数据模拟
        Map<String, String> mockMap = new HashMap<>();
        mockMap.put(ConfigPropertyEnum.TEST.key(), "realValue");

        configs = mockMap;
        // 一般配置中心都能添加监听器,以便对配置改变时能做更新处理
    }

    private String getValue(IConfigPropertyEnum property) {
        String value = get(property.key());
        if(value == null) {
            System.out.println("config key error");
            value = property.defaultValue();
        }

        return value;
    }

    public String get(String key) {
        return configs.get(key);
    }

    public String get(IConfigPropertyEnum property) {
        return getValue(property);
    }

    // 还有一些别的asInteger之类的方法可以添加
    public Long asLong(IConfigPropertyEnum property) {
        return Long.parseLong(getValue(property));
    }

    public static ConfigProperties newInstance() {
        return ConfigPropertiesHolder.INSTANCE;
    }



}


相关文章

网友评论

      本文标题:项目使用配置中心简化处理

      本文链接:https://www.haomeiwen.com/subject/uwtpihtx.html