栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

雪花算法生成工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

雪花算法生成工具类

可以直接使用的雪花算法生成工具类

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;


public class SnowflakeIdWorker {

    // ==============================Fields===========================================
    
    private final long twepoch = 1611043703161L;

    
    private final long workerIdBits = 5L;

    
    private final long dataCenterIdBits = 5L;

    
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    
    private final long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);

    
    private final long sequenceBits = 12L;

    
    private final long workerIdShift = sequenceBits;

    
    private final long dataCenterIdShift = sequenceBits + workerIdBits;

    
    private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;

    
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    
    private long workerId;

    
    private long dataCenterId;

    
    private long standbyDatacenterId;

    
    private long sequence = 0L;

    
    private long lastTimestamp = -1L;

    
    private boolean isTimestampBack = false;

    // ==============================Constructors=====================================
    
    private static final long MAX_BACKWARD_MS = 3;

    
    SnowflakeIdWorker(long workerId, long datacenterId, long standbyDatacenterId) {
        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));
        }
        if (standbyDatacenterId > maxDataCenterId || standbyDatacenterId < 0) {
            throw new IllegalArgumentException(String.format("standby datacenter Id can't be greater than %d or less than 0", maxDataCenterId));
        }
        if (datacenterId == standbyDatacenterId) {
            throw new IllegalArgumentException("datacenter Id can't equal to standby datacenter Id.");
        }
        this.workerId = workerId;
        this.dataCenterId = datacenterId;
        this.standbyDatacenterId = standbyDatacenterId;
    }

    // ==============================Methods==========================================

    
    synchronized long nextId() {
        long timestamp = timeGen();

        // 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过
        if (timestamp < lastTimestamp) {
            // 如果时钟回拨在可接受范围内, 等待即可
            long offset = lastTimestamp - timestamp;
            if (offset <= MAX_BACKWARD_MS) {
                try {
                    //睡(lastTimestamp - currentTimestamp)ms让其追上
                    LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(offset));

                    timestamp = timeGen();
                    //如果当前时间还是小于上一次ID生成的时间戳,这时启用备用的datacenterId
                    if (timestamp < lastTimestamp) {
                        isTimestampBack = true;
                        //服务器时钟被调整了
                        //log.error(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
                        //throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
                    } else {
                        isTimestampBack = false;
                    }
                } catch (Exception e) {
                    //log.error(e);
                }
            }
        }

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

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

        //要使用的datacenterId
        long datacenterIdToUse = isTimestampBack ? standbyDatacenterId : dataCenterId;

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

    
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    private volatile static SnowflakeIdWorker snowflakeIdWorker;

    public static SnowflakeIdWorker getInstance() {
        if (snowflakeIdWorker == null) {
            synchronized (SnowflakeIdWorker.class) {
                if (snowflakeIdWorker == null) {
                    snowflakeIdWorker = new SnowflakeIdWorker(1, 0,11);
                }
            }
        }
        return snowflakeIdWorker;
    }

    
    public static String getNextId() {
        return String.valueOf(getInstance().nextId());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/839121.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号