雪花算法的研究

雪花算法有64位bit 里面 单机是通过时间戳加自增序号表示唯一,在集群场景下每个机器的机器id不一样也能保证唯一,看下了雪花算法的bit结构发现都是做位移操作和与或操作,刚好之前分析bitset源码也是需要操作bit通过位移操作和与或操作. 试着尝试在雪花算法里面加入一点自己的东西couponType(优惠券类型)占用4bit, 把自增的减少到8 bit最大值从4096变成256, 在单机每毫米256个(1s 就是256000个) 完全足够

package com.lipenghui.demo;

import java.util.Date;

/**
 * bst
 */
public class IdWorker {
    //开始时间截 (2015-01-01)
    private final long twepoch = 1489111610226L;
    //机器ID所占位置
    private final long workerIdBits = 5L;
    //数据标识所占位数
    private final long dataCenterIdBits = 5L;
    //支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    //支持的最大数据标识id,结果是31
    private final long maxdataCenterId = -1L ^ (-1L << dataCenterIdBits);
    //序列在id中占的位数
    private final long sequenceBits = 8L;

    private final long couponTypeBits = 4L;
    //优惠券类型向左移8位
    private final long couponTypeShift = sequenceBits;
    //机器ID向左移12位
    private final long workerIdShift = sequenceBits + couponTypeBits;
    //数据标识id向左移17位(8+4+5)
    private final long dataCenterIdShift = sequenceBits + couponTypeBits + workerIdBits;
    //时间截向左移22位(8+4+5+5)
    private final long timestampLeftShift = sequenceBits + couponTypeBits  + workerIdBits + dataCenterIdBits;
    //生成序列的掩码,这里为255
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    //工作机器ID(0~31)
    private long workerId;

    //数据中心ID(0~31)
    private long dataCenterId;
    //优惠券类型
    private long couponType;

    //毫秒内序列(0~4095)
    private long sequence = 0L;

    //上次生成ID的时间截
    private long lastTimestamp = -1L;

    /**
     *
     * @param workerId 工作机器ID(0~31)
     * @param dataCenterId 数据中心ID(0~31)
     */
    public IdWorker(long workerId, long dataCenterId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format(
                    "worker Id can't be greater than %d or less than 0",
                    maxWorkerId));
        }
        if (dataCenterId > maxdataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format(
                    "datacenter Id can't be greater than %d or less than 0",
                    maxdataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return
     */
    public synchronized long nextId(long couponType) {
        this.couponType = couponType;
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format(
                    "Clock moved backwards.  Refusing to generate id for %d milliseconds",
                    lastTimestamp - timestamp));
        }

        //如果是同一时间生成的,则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {//时间戳改变,毫秒内序列重置
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift)
                | (dataCenterId << dataCenterIdShift)
                | (workerId << workerIdShift)
                | (couponType << couponTypeShift)
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒,直到获得新的时间戳
     * @param lastTimestamp
     * @return
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }


    /**
     * 返回以毫秒为单位的当前时间
     * @return
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        IdWorker idWorker = new IdWorker(1,0);
        for (long i = 0L; i < 3L; i++) {

        }
//        System.out.println(idWorker.nextId(1L));
//        System.out.println(idWorker.nextId(2L));
//        System.out.println(idWorker.nextId(1L));
//        System.out.println(idWorker.nextId(1L));
//        System.out.println(idWorker.nextId(2L));
//        System.out.println(idWorker.nextId(2L));
//        System.out.println(idWorker.nextId(2L));

        //雪花算法反推
        // 00 01 10 11
        // 000 001  011 111 100 101 010 110

        long a = idWorker.nextId(2L);


        System.out.println(a);
        System.out.println(new Date((a >> 22) + idWorker.twepoch));
        System.out.println((a >> 22) & ~(-1L << 8)); // sequence
        System.out.println((a >> (8)) & ~(-1L << (4)));// dwId
        System.out.println((a >> 12) & ~(-1L << 5));// workerId
        System.out.println((a >> 17) & ~(-1L << 5)); // dataCenterId
        System.out.println((a  >> 22) + idWorker.twepoch);// timestamp


//        long sequenceMask = -1L ^ (-1L << 8L);
//        System.out.println(sequenceMask);
//        for (long i = 0; i <1024 ; i++) {
//            long sequence = (i + 1) & sequenceMask;
//
//            System.out.println(sequence);
//        }


    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值