雪花算法代码

工具类:

@Slf4j
public class SnowflakeIdWorker {
    // 工作机器ID(0~31)
    private final long workerId;
    //数据中心ID(0~31)
    private final long dataCenterId;
    //毫秒内序列(0~4095)
    private long sequence = 0L;

    public SnowflakeIdWorker(long workerId, long dataCenterId) {
        // sanity check for workerId
        // 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
        long maxWorkerId = ~(-1L << workerIdBits);
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        // 支持的最大数据标识id,结果是31
        long maxDecenterId = ~(-1L << decenterIdBits);
        if (dataCenterId > maxDecenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("dataCenter Id can't be greater than %d or less than 0", maxDecenterId));
        }
        log.info("worker starting. timestamp left shift = {}, dataCenter id bits = {}, worker id bits = {}, sequence bits = {}, workerid = {}, dataCenterId = {}",
                timestampLeftShift, decenterIdBits, workerIdBits, sequenceBits, workerId, dataCenterId);

        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    ///长度为5位
    private final long workerIdBits = 5L;
    private final long decenterIdBits = 5L;
    //序列在id中占的位数
    private final long sequenceBits = 12L;
    //时间戳需要左移位数 12+5+5=22位
    private final long timestampLeftShift = sequenceBits + workerIdBits + decenterIdBits;
    //上次时间戳,初始值为负数
    private long lastTimestamp = -1L;
    private static final SnowflakeIdWorker idWorker;
    static {
        idWorker = new SnowflakeIdWorker(getWorkId(), getDataCenterId());
    }

    /**
     * 获得下一个ID (该方法是线程安全的)
     *
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        //获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常
        if (timestamp < lastTimestamp) {
            log.error("clock is moving backwards.  Rejecting requests until : {}.", lastTimestamp);
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds",
                    lastTimestamp - timestamp));
        }
        //获取当前时间戳如果等于上次时间戳(同一毫秒内),则在序列号加一;否则序列号赋值为0,从0开始。
        if (lastTimestamp == timestamp) {
            // 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
            long sequenceMask = ~(-1L << sequenceBits);
            sequence = (sequence + 1) & sequenceMask;
            // 毫秒内序列溢出
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        //将上次时间戳值刷新
        lastTimestamp = timestamp;
        /*
         * 返回结果:
         * (timestamp - twepoch) << timestampLeftShift) 表示将时间戳减去初始时间戳,再左移相应位数
         * (datacenterId << datacenteridshift) 表示将数据id左移相应位数
         * (workerId << workerIdShift) 表示将工作id左移相应位数
         * | 是按位或运算符,例如:x | y,只有当x,y都为0的时候结果才为0,其它情况结果都为1。
         * 因为个部分只有相应位上的值有意义,其它位上都是0,所以将各部分的值进行 | 运算就能得到最终拼接好的id
         */        //初始时间戳
        long twepoch = 1577808000000L;
        //工作id需要左移的位数,12位
        //数据id需要左移位数 12+5=17位
        long datacenteridshift = sequenceBits + workerIdBits;
        return ((timestamp - twepoch) << timestampLeftShift) |
                (dataCenterId << datacenteridshift) |
                (workerId << sequenceBits) |
                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();
    }

    private static Long getWorkId() {
        try {
            String hostAddress = Inet4Address.getLocalHost().getHostAddress();
            char[] chars = hostAddress.toCharArray();
            int sums = 0;
            for (int b : chars) {
                sums += b;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            // 如果获取失败,则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }
    }

    private static Long getDataCenterId() {
        try {
            char[] chars = Inet4Address.getLocalHost().getHostName().toCharArray();

            int sums = 0;
            for (int i : chars) {
                sums += i;
            }
            return (long) (sums % 32);
        } catch (UnknownHostException e) {
            // 如果获取失败,则使用随机数备用
            return RandomUtils.nextLong(0, 31);
        }

    }


    // 静态工具类
    public static Long generateId() {
        return idWorker.nextId();
    }

测试类:

public static void main(String[] args) {
     System.out.println(SnowflakeIdWorker.generateId());
}

你可能感兴趣的:(java)