package com.grid.service;
public class SnowflakeIdWorker {
/**
* 雪花算法解析 結構 snowflake的結構如下(每部分用-分開):
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000
* 第一位為未使用,接下來的41位為毫秒級時間(41位的長度可以使用69年),然后是5位datacenterId和5位workerId(10
* 位的長度最多支持部署1024個節點) ,最后12位是毫秒內的計數(12位的計數順序號支持每個節點每毫秒產生4096個ID序號)
*
* 一共加起來剛好64位,為一個Long型。(轉換成字符串長度為18)
*
*/
// ==============================Fields===========================================
/** 開始時間截 (2015-01-01) */
private final long twepoch = 1489111610226L;
/** 機器id所占的位數 */
private final long workerIdBits = 5L;
/** 數據標識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) */
private final long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
/** 生成序列的掩碼,這里為4095 (0b111111111111=0xfff=4095) */
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作機器ID(0~31) */
private long workerId;
/** 數據中心ID(0~31) */
private long dataCenterId;
/** 毫秒內序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的時間截 */
private long lastTimestamp = -1L;
// ==============================Constructors=====================================
/**
* 構造函數
* @param workerId 工作ID (0~31)
* @param dataCenterId 數據中心ID (0~31)
*/
public SnowflakeIdWorker(long workerId, long dataCenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("workerId can't be greater than %d or less than 0", maxWorkerId));
}
if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
throw new IllegalArgumentException(String.format("dataCenterId can't be greater than %d or less than 0", maxDataCenterId));
}
this.workerId = workerId;
this.dataCenterId = dataCenterId;
}
// ==============================Methods==========================================
/**
* 獲得下一個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));
}
// 如果是同一時間生成的,則進行毫秒內序列
// sequenceMask 為啥是4095 2^12 = 4096
if (lastTimestamp == timestamp) {
// 每次+1
sequence = (sequence + 1) & sequenceMask;
// 毫秒內序列溢出
if (sequence == 0) {
// 阻塞到下一個毫秒,獲得新的時間戳
timestamp = tilNextMillis(lastTimestamp);
}
}
// 時間戳改變,毫秒內序列重置
else {
sequence = 0L;
}
// 上次生成ID的時間截
lastTimestamp = timestamp;
// 移位並通過或運算拼到一起組成64位的ID
// 為啥時間戳減法向左移動22 位 因為 5位datacenterid
// 為啥 datCenterID向左移動17位 因為 前面有5位workid 還有12位序列號 就是17位
//為啥 workerId向左移動12位 因為 前面有12位序列號 就是12位
System.out.println(((timestamp - twepoch) << timestampLeftShift) //
| (dataCenterId << dataCenterIdShift) //
| (workerId << workerIdShift) //
| sequence);
return ((timestamp - twepoch) << timestampLeftShift) //
| (dataCenterId << dataCenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
* 阻塞到下一個毫秒,直到獲得新的時間戳
* @param lastTimestamp 上次生成ID的時間截
* @return 當前時間戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒為單位的當前時間
* @return 當前時間(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
// ==============================Test=============================================
/** 測試 */
public static void main(String[] args) {
System.out.println(System.currentTimeMillis());
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1, 1);
long startTime = System.nanoTime();
for (int i = 0; i < 50000; i++) {
long id = idWorker.nextId();
System.out.println(id);
}
System.out.println((System.nanoTime() - startTime) / 1000000 + "ms");
}
}