【Vesta发号器源码】IpConfigurableMachineIdProvider

Vesta发号器源码解析——IpConfigurableMachineIdProvider

利用IP持有machineId的模式

字段和属性

    //日志
    private static final Logger log = LoggerFactory
            .getLogger(IpConfigurableMachineIdProvider.class);

    //MachineId存储
    private long machineId;
    
    //ip映射表
    private Map ipsMap = new HashMap();
    
    //默认无参构造方法
    //记录日志
    public IpConfigurableMachineIdProvider() {
        log.debug("IpConfigurableMachineIdProvider constructed.");
    }
    
    //根据参数ips,ip信息构造
    public IpConfigurableMachineIdProvider(String ips) {
        //解析并处理IP
        setIps(ips);
        //初始化
        init();
    }

初始化方法

    public void init() {
        //读取主机IP地址
        String ip = IpUtils.getHostIp();
        //判断ip地址是否取到,如果没取到抛出异常,记录日志,终止初始化
        if (StringUtils.isEmpty(ip)) {
            String msg = "Fail to get host IP address. Stop to initialize the IpConfigurableMachineIdProvider provider.";

            log.error(msg);
            throw new IllegalStateException(msg);
        }
        
        //判断IP是否有记录,如果没有,记录日志抛出异常
        if (!ipsMap.containsKey(ip)) {
            String msg = String
                    .format("Fail to configure ID for host IP address %s. Stop to initialize the IpConfigurableMachineIdProvider provider.",
                            ip);

            log.error(msg);
            throw new IllegalStateException(msg);
        }
        
        //获取IP对应的id
        machineId = ipsMap.get(ip);
        //记录日志
        log.info("IpConfigurableMachineIdProvider.init ip {} id {}", ip,
                machineId);
    }

设置IPs


    public void setIps(String ips) {
        log.debug("IpConfigurableMachineIdProvider ips {}", ips);
        //参数校验
        if (!StringUtils.isEmpty(ips)) {
            //逗号分隔的ip地址列表
            String[] ipArray = ips.split(",");
            //分配ID
            for (int i = 0; i < ipArray.length; i++) {
                ipsMap.put(ipArray[i], (long) i);
            }
        }
    }

getter和setter

    public long getMachineId() {
        return machineId;
    }

    public void setMachineId(long machineId) {
        this.machineId = machineId;
    }

你可能感兴趣的:(【Vesta发号器源码】IpConfigurableMachineIdProvider)