分布式唯一主键生成解决方案-雪花算法(SnowFlake)

目录

1、基本原理

2、SnowFlake的结构如下(每部分用-分开):

3、优缺点

4、算法实现

5、测试

SnowFlake算法,是Twitter开源的分布式ID生成算法。其核心思想就是使用使用一个64为的Long类型的数据作为全局唯一ID。

1、基本原理

我们都知道计算机语言是2进制语言,则计算机存放数字都是存放数字的补码。

例如:-1(一般一个byte为8位,-1L就是64个1)的补码是1111 1111 反码是1111 1110 原码是1000 0001。

另外在计算中通常把最高位当成是符号位,“0”:表示负数,“1”:表示正数

 ^ 表示异或 即:相同为0,相异为1; << 左移运算符 即:-1L<<5L 表示1110 0000;

例如:(-1L^(-1L<<5L))

表示:1111 1111^1110 0000

结果:0001 1111

利用8421码进行转换  128 64 32 16 8 4 2 1  转换为十进制为16+8+4+2+1=31

2、SnowFlake的结构如下(每部分用-分开):

 0 - 0000000000 0000000000 0000000000 0000000000 0000000000 0 – 0000000000 00 – 00000000 0000

 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0

 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)得到的值,这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69

 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId,这个位数是可以修改的

 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号

 以上加起来刚好64位,为一个Long型。

3、优缺点

优点:整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高

缺点:如果节点上的时间倒退可能会出现重复ID的情况。

4、算法实现

public class GeneratorIdUtil {

    private static Logger logger = LoggerFactory.getLogger(GeneratorIdUtil.class);

    /**
     * 开始时间截,这里设置为项目开始的时间2018-05-24 从2018-05-24算起大约能够使用69年
     */
    private final long twepoch = 1527150129903L;

    /**
     * 机器id所占的位数,这里设置位10L,因为datacenterIdBits不需要
     * 如果workerIdBits=5L 则datacenterIdBits=5L
     */
    private final long workerIdBits = 10L;

    /*
     * 数据标识id所占的位数,根据项目需求可以不用
     */
    // 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 = 12L;

    /**
     * 机器ID向左移12位
     */
    private final long workerIdShift = sequenceBits;

    /*
     * 数据标识id向左移17位(12+5)
     */
    // private final long datacenterIdShift = sequenceBits + workerIdBits;

    /**
     * 时间截向左移22位(5+5+12)
     * //+ datacenterIdBits;
     */
    private final long timestampLeftShift = sequenceBits + workerIdBits;

    /**
     * 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095)
     */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

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

    /**
     * 数据中心ID(0~31)
     */
    private long datacenterId;

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

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

    /**
     * 构造函数
     *
     * @param workerId 工作ID (0~1023)
     */
    private GeneratorIdUtil(long workerId) {
        logger.info("workerId : {}", workerId);
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.workerId = workerId;
    }

    /**
     * 构造函数
     */
    private GeneratorIdUtil() {
        this.workerId = getIdWorker();
        logger.info("workerId : {}", workerId);
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
    }


    /**
     * 获得下一个ID (该方法是线程安全的)
     *
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        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)
                       | sequence;
    }

    /**
     * 阻塞到下一个毫秒,直到获得新的时间戳
     *
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

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

    /**
     * 获取机器编号,设置机器编号的方式有很多,这里根据业务需求取IP地址的后三位
     * 根据前面分析该ID位0-1023
     * param
     */
    private int getIdWorker() {
        InetAddress addr = null;
        String ip = "";
        try {
            addr = InetAddress.getLocalHost();
            /*获取本机IP*/
            ip = addr.getHostAddress();
            logger.info("本机IP : {}  ", ip);
            return Integer.parseInt(ip.split("\\.")[3]);
        } catch (Exception e) {
            logger.error("获取机器编号错误 : {}  ", ip + e);
        }
        return 0;
    }
}

5、测试

这里只做简单的测试,不考虑数据库性能。

测试电脑配置如下

  1. 机器ID为1023,测试代码如下:
   @SneakyThrows
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis() / 1000;
        GeneratorIdUtil generatorIdUtil = new GeneratorIdUtil(1023);
        int count = 1;
        CountDownLatch countDownLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            ThreadPoolUtils.getThreadPool().execute(() -> {
                        try {
                            for (int k = 0; k < 1000000; k++) {
                                generatorIdUtil.nextId();
                            }
                        } finally {
                            countDownLatch.countDown();
                        }
                    }
            );
        }
        ThreadPoolUtils.shutdown();
        countDownLatch.await();
        long endTime = System.currentTimeMillis() / 1000;
        logger.info("目标执行时间 : {} s", (endTime - startTime));
    }

    public class ThreadPoolUtils {
	    private static final ExecutorService threadPool;
	    CountDownLatch countDownLatch;
	    static{
		    ThreadFactory threadFactory = new ThreadFactoryBuilder().build();
		        threadPool = new ThreadPoolExecutor(20, 20, 50,
				    TimeUnit.SECONDS, new ArrayBlockingQueue<>(1),
				    threadFactory, new ThreadPoolExecutor.AbortPolicy());
	    }
	
        public static ExecutorService getThreadPool() {
            return threadPool;
        }
    
        public static void shutdown() {
		    threadPool.shutdown();
        }
}

测试结果

线程数

量级

耗时

1

10000000

2~3s

1

1000000

3ms

10

1000000

2~3s

10

10000000

25s

                                                                                 

                                                                                 欢迎扫码关注公众号

发布了13 篇原创文章 · 获赞 11 · 访问量 9612
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章