通用接口

public interface XConfig {
    Properties properties = new Properties();

    default Properties getProperties() {
        return properties;
    }

    /**
     * 用来接收各种输入类型, 不需要在使用的时候进行考虑类型
     *
     * @param key
     * @param value
     * @param <V>
     */
    static <V> void setProperty(String key, V value) {
        if (value instanceof String) {
            // value为字符串类型
            properties.setProperty(key, (String) value);
        } else if (value instanceof Class) {
            // 如果是一个类的类型
            properties.setProperty(key, ((Class<?>) value).getName());
        } else {
            // value为数值等其他基本类型
            properties.setProperty(key, String.valueOf(value));
        }

    }

    void init();
}

自定义配置类

public class XBaseConfig implements XConfig {

    // 配置需要设置的各项配置属性
    @Override
    public void init() {

        XConfig.setProperty(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, "hadoop001:9092,hadoop002:9092,hadoop003:9092");

        XConfig.setProperty(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        XConfig.setProperty(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        XConfig.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        XConfig.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    }
}

工具类

public class XUtils {

    //整合所有的配置类
    public static Properties getSystemResource(List<Class<? extends XConfig>> configClasses) {
        Properties properties = new Properties();
        try {
            for (Class<? extends XConfig> configClass : configClasses) {
                XConfig xConfig = configClass.newInstance();
                xConfig.init();
                Properties propertiesX = xConfig.getProperties();
                propertiesX.forEach((key, value) -> properties.setProperty((String) key, (String) value));
            }
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }

        return properties;
    }
}

使用示例

    @Test
    public void getConfigClassTest() {
        // 这里可以添加多个配置类
        List<Class<? extends XConfig>> classes = new ArrayList<>();
        classes.add(XBaseConfig.class);

        Properties properties = getSystemResource(classes);
        properties.forEach((key, value) -> System.out.println(key + "=" + value));
    }

image-20221104214232986


   转载规则


《》 熊水斌 采用 知识共享署名 4.0 国际许可协议 进行许可。
 上一篇
函数式编程概述函数式编程的作用 公司使用的主流 大数量下处理集合效率高 代码可读性高 消灭嵌套地狱 函数式编程思想关注点: 函数对数据进行的什么操作, 即关注方法参数和方法体 优点: 代码简洁, 开发快速 接近自然语言, 易于理解 易于
2022-11-11
下一篇 
分库分表分库分表是什么为什么要分库分表? 分库分表的方式垂直分表按字段使用频率的高低来拆分表, 频率高的字段放入同一张表, 频率低的字段放入另一张表. 优点 数据库以页为存储单位, 单页内数据行越多, 数据库性能越好 数据库以行为单位将
2022-11-11
  目录