【工具类】系列一 配置工具类 Yaml Config

工具类列文章,主要记录自己开发过程中用到的工具类,方便开发时开箱即用。

Java开发时,经常使用property文件来配置,但是个人感觉可读性和层级结构不太明了。比较推荐yaml方式来配置。

yaml入门参考:

https://www.runoob.com/w3cnote/yaml-intro.html

https://www.jianshu.com/p/97222440cd08

 

下面记录的是,加载yaml配置类

/**
 * load configuration file "application-{profile}.yaml, and then get value from config file. <br />
 *
 * <ul>usage as follows:
 *     <li>get single value: Config.getString("redis.port")</li>
 *     <li>get multiple value: Config.get(String key, Class<T> claz) </li>
 * </ul>
 *
 * @author adore.chen
 * @date 2020-04-29
 */
@Slf4j
public class Config {

    public static String PROFILE_KEY = "spring.profiles.active";
    public static String PROFILE_DEFAULT = "develop";

    private static final Map<String, Object> config = new HashMap<>();

    static {
        // initial loading configuration
        String profile = System.getProperty(PROFILE_KEY, PROFILE_DEFAULT);
        String file = "application-" + profile + ".yaml";
        load(file);
    }

    private Config() {

    }

    public static void load(String file) {
        if (!file.endsWith(".yaml")) {
            throw new IllegalArgumentException("Only Support *.yaml configuration file.");
        }

        System.out.println("==> load config file: " + file);
        try (InputStream inputStream = Config.class.getResourceAsStream("/" + file)) {
            Yaml yaml = new Yaml();
            Map<String, Object> map = yaml.load(inputStream);
            config.putAll(map);
        } catch (Exception e) {
            log.error("load config file {} error", file, e);
        }

    }

    /**
     * return config value as String.
     * @param key
     * @return
     */
    public static String getString(String key) {
        return get(key).toString();
    }

    public static int getInt(String key) {
        return (Integer) get(key);
    }

    public static <T> T get(String key, Class<T> claz) {
        return (T) get(key);
    }

    /**
     * support java properties access pattern.  key = path1.path2.path3;
     * @param key
     * @return
     */
    private static Object get(String key) {
        // access recursive by path
        String[] paths = key.split("\\.");
        Map<String, Object> map = config;
        for (int index = 0; index < paths.length - 1; index++) {
            // get sub-map
            map = (Map<String, Object>)map.get(paths[index]);
        }

        Object obj = map.get(paths[paths.length - 1]);
        Check.checkNonNull(obj, "NOT FOUND config value for key: " + key);
        return obj;
    }

    /**
     * return all config key/values.
     * @return
     */
    public static Map<String, Object> getAll() {
        return config;
    }

}

 

配置文件 application-develop.yaml

# Redis Configuration
redis:
  host: apn2.cache.amazonaws.com
  port: 6379


# Kafka Configuration
kafka:
  config:
    key.deserializer: "org.apache.kafka.common.serialization.StringDeserializer"
    value.deserializer: "org.apache.kafka.common.serialization.StringDeserializer"
    auto.offset.reset: "latest"
    enable.auto.commit: true
    auto.commit.interval.ms:  30000

  source:
    - bootstrap.servers: "kafka-p1.test.net:9092"
      topics:
        - "order.payment.1"

    - bootstrap.servers: "kafka-member.test.net:9092"
      topics:
        - "member.join.1"
        - "member.log-in-out.1"
        - "member.check-pincode.1"


 

测试用例,展示使用方式:

@Test
public void testGet() {
    String key = "redis.host";
    String expected = "apn2.cache.amazonaws.com";

    String actual = Config.getString(key);
    Assert.assertEquals(expected, actual);
}

@Test
public void testGetList() {
    String key = "kafka.source";
    List<Map<String, Object>> actual = Config.get(key, List.class);
    System.out.println(actual.get(0).get("topics"));

    System.out.println(Config.get("kafka", Map.class));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值