ZkClusterConfig.java 2.51 KB
package io.mycat.zkcluster;

import com.google.common.base.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by xueyin on 2018/11/29.
 * 集群配置, 对应文件cluster.properties
 */
public class ZkClusterConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(ZkClusterConfig.class);

    private static final String CONIFG_FILE = "/cluster.properties";
    private static final String CLUSTER_MODE = "clusterMode";
    private static final String CLUSTER_NAME = "clusterName";
    private static final String ZK_URL = "zkUrl";

    // 默认不开启集群模式
    public static final boolean DEFAULT_CLUSTER_MODE = false;

    // 默认集群名称为front
    public static final String DEFAULT_CLUSTER_NAME = "front";

    private Boolean clusterMode = false;
    private String clusterName = "front";
    private String zkUrl = "";

    private static ZkClusterConfig CFG_INSTANCE = new ZkClusterConfig();

    public ZkClusterConfig() {
        loadConfig();
    }

    public static ZkClusterConfig getInstance() {
        return CFG_INSTANCE;
    }

    public Boolean getClusterMode() {
        return clusterMode;
    }

    public String getClusterName() {
        return clusterName;
    }

    public String getZkUrl() {
        return zkUrl;
    }

    private void loadConfig() {
        Properties properties = new Properties();
        try {
            properties.load(ZkClusterConfig.class.getResourceAsStream(CONIFG_FILE));
        } catch (IOException e) {
            LOGGER.error("clusterConfig load fail: ", e);
            throw new RuntimeException("load cluster config file fail.");
        }

        String mode = properties.getProperty(CLUSTER_MODE);
        String name = properties.getProperty(CLUSTER_NAME);
        String url = properties.getProperty(ZK_URL);

        if ( Strings.isNullOrEmpty(mode) || Boolean.valueOf(mode) == null) {
            LOGGER.error("invalid cluster mode config: ", mode);
            throw new RuntimeException("invalid cluster mode config.");
        }

        Boolean bMode = Boolean.valueOf(mode);
        if (bMode == true
                && (Strings.isNullOrEmpty(name)
                    || Strings.isNullOrEmpty(url))) {
            LOGGER.error("invalid cluster name or zkurl config.");
            throw new RuntimeException("invalid cluster name or zkurl config.");
        }

        this.clusterMode = bMode;
        this.clusterName = name;
        this.zkUrl = url;
    }

}