自动ID的生成

自动ID的生成

1.多机集群的环境下生成的ID

/*多机或集群环境下唯一ID生成实现类。
* 生成方法:毫秒时间戳(43位,最大时间到2248年)+(20位=5位机器码+15位循环自增数)
* 机器码计算方法:mac或网络地址和进程号连接后的哈希。
* 其它网络场景:5位机器码理论最大支持32台机器,优先取网络地址最后10位,获取不到则取mac最后10位,否则取随机数0-31
*/
@Override
public long getIdentityid() {
    long currentTime = System.currentTimeMillis(); // 当前系统的日期
    while (!identityidValid.valid(currentTime)) {
        try {
            Thread.sleep(Constants.ONE);
        } catch (InterruptedException e) {
            logger.error("Thread sleep error!", e);
        }
        currentTime = System.currentTimeMillis();
    }
    int incNumber = atomicInc.getAndIncrement();
    return (currentTime - BENCHMARK_TIME) << Constants.TWENTY | (machineId << 15) | (incNumber & INCNUMBER_AND_NUMBER);

其中identityidValid是检测ID是否重复

private class IdentityidValid {
    //时间
    public long time;

    //生成数量
    public int count;

    IdentityidValid(long time, int count) {
        this.time = time;
        this.count = count;
    }

    public boolean valid(long time) {
        if (time != this.time) {
            this.time = time;
            this.count = 0;
            return true;
        }
        if (this.count < INCNUMBER_AND_NUMBER) {
            this.count++;
            return true;
        }
        return false;
    }
}

2.单机的生成方法

/**
 * 生成方法:13位毫秒时间戳+6位循环自增数。
 */
@Override
public long getIdentityid() {
    long identityid = (System.currentTimeMillis() - BENCHMARK_TIME) << Constants.TWENTY;
    int incNumber = atomicInc.getAndIncrement(); //随机数
    return identityid | (incNumber & INCNUMBER_AND_NUMBER);
    
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值