ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java 雪花算法

2021-10-12 16:33:16  阅读:207  来源: 互联网

标签:java sequence timestamp 雪花 long 算法 private bit id


SnowFlake 算法,是 Twitter 开源的分布式 id 生成算法。

其核心思想是,使用一个 64 bit 的 long 型的数字作为全局唯一 id。

 

这个64 bit 的 long 型数字的储存模型如下:

第一部分,占用 1 bit:0。

第二部分,占用 41 bit:表示的是时间戳。

第三部分,占用 5  bit:表示的是机房 id。

第四部分,占用 5  bit:表示的是机器 id。

第五部分,占用 12  bit:表示的是序号。

 

代码如下:

package com.demo.springboot.common;

public class IdWorker {
    //因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。
    //代表一毫秒内生成的多个id的最新序号 2进制12位 2^12 - 1 = 4095个
    private long sequence;
    //机器ID 2进制5位 2^5 - 1 = 31个
    private long workerId;
    //机房ID 2进制5位 2^5 - 1 = 31个
    private long datacenterId;
    //设置一个时间初始值 2进制41位 2^41 - 1差不多可以用69年
    //2021-01-01 => 1609430400000
    private long epoch = 1609430400000L;
    //12位的最新序号
    private long sequenceBits = 12L;
    //5位的机器id
    private long workerIdBits = 5L;
    //5位的机房id
    private long datacenterIdBits = 5L;

    //这个是二进制运算,就是5 bit机器id最大值31
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);
    //这个是一个意思,就是5 bit机房id最大值31
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    private long sequenceMask = -1L ^ (-1L << sequenceBits);
    private long workerIdShift = sequenceBits;
    private long datacenterIdShift = sequenceBits + workerIdBits;
    private long timestampShift = sequenceBits + workerIdBits + datacenterIdBits;

    //记录产生时间毫秒数,判断是否是同1毫秒
    private long lastTimestamp = -1L;

    public IdWorker(long datacenterId, long workerId, long sequence) {
        //检查机房id和机器id 不能超过31 不能小于0
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.datacenterId = datacenterId;
        this.workerId = workerId;
        this.sequence = sequence;
    }

    //生成一个全局唯一的id
    public synchronized long nextId() {
        //获取当前时间戳,单位毫秒
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            System.err.printf(
                    "clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                            lastTimestamp - timestamp));
        }
        //同一个毫秒内生成多个id,seqence序号递增1,最大是4095
        if (lastTimestamp == timestamp) {
            //这个位运算避免sequence超过4095
            sequence = (sequence + 1) & sequenceMask;
            //当某一毫秒产生的id数超过4095,系统会进入等待,直到下一毫秒继续产生id
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        //记录一下最近一次生成id的时间戳,单位毫秒
        lastTimestamp = timestamp;
        //二进制位运算操作,生成一个64bit的id
        return ((timestamp - epoch) << timestampShift) |
                (datacenterId << datacenterIdShift) |
                (workerId << workerIdShift) | sequence;
    }

    //当某一毫秒产生的id数超过4095,系统会进入等待,直到下一毫秒继续产生id
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    //获取当前时间戳
    private long timeGen(){
        return System.currentTimeMillis();
    }

    public static void main(String[] args) {
        IdWorker worker = new IdWorker(1,1,1);
        for (int i = 0; i < 10; i++) {
            System.out.println(worker.nextId());
        }
    }

}

  

标签:java,sequence,timestamp,雪花,long,算法,private,bit,id
来源: https://www.cnblogs.com/by-lhc/p/15398415.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有