雪花算法SnowFlake可以保證:
1.所有生成的id按時間趨勢遞增
2.整個分布式系統(tǒng)內(nèi)不會產(chǎn)生重復id(通過workerId和datacenterId來做區(qū)分)
算法實現(xiàn)
import java.util.Random;
public class IdWorker {
//下面兩個每個5位,加起來就是10位的工作機器id
private long workerId; //工作ID 2進制5位 數(shù)值0-31
private long datacenterId; //數(shù)據(jù)id 2進制5位 數(shù)值0-31
//12位的序列號
private long sequence;
public IdWorker(long workerId, long datacenterId, long sequence) {
// sanity check for workerId
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));
}
System.out.printf("worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",
timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
}
//初始時間戳
private long twepoch = 1288834974657L;
//長度為5位
private long workerIdBits = 5L;
private long datacenterIdBits = 5L;
//最大值
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
//序列號id長度
private long sequenceBits = 12L;
//序列號最大值
private long sequenceMask = -1L ^ (-1L << sequenceBits);
//工作id需要左移的位數(shù)器瘪,12位
private long workerIdShift = sequenceBits;
//數(shù)據(jù)id需要左移位數(shù) 12+5=17位
private long datacenterIdShift = sequenceBits + workerIdBits;
//時間戳需要左移位數(shù) 12+5+5=22位
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
//上次時間戳翠储,初始值為負數(shù)
private long lastTimestamp = -1L;
//下一個ID生成算法
public synchronized long nextId() {
long timestamp = timeGen();
//獲取當前時間戳如果小于上次時間戳,則表示時間戳獲取出現(xiàn)異常
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));
}
//獲取當前時間戳如果等于上次時間戳(同一毫秒內(nèi))橡疼,則在序列號加一援所;否則序列號賦值為0,從0開始欣除。
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
//將上次時間戳值刷新
lastTimestamp = timestamp;
/**
* 返回結(jié)果:
* (timestamp - twepoch) << timestampLeftShift) 表示將時間戳減去初始時間戳住拭,再左移相應位數(shù)
* (datacenterId << datacenterIdShift) 表示將數(shù)據(jù)id左移相應位數(shù)
* (workerId << workerIdShift) 表示將工作id左移相應位數(shù)
* | 是按位或運算符,例如:x | y,只有當x滔岳,y都為0的時候結(jié)果才為0杠娱,其它情況結(jié)果都為1。
* 因為個部分只有相應位上的值有意義谱煤,其它位上都是0摊求,所以將各部分的值進行 | 運算就能得到最終拼接好的id
*/
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) |
sequence;
}
/**
* 獲取時間戳,并與上次時間戳比較
* @param lastTimestamp
* @return
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 獲取系統(tǒng)時間戳
*/
private long timeGen() {
return System.currentTimeMillis();
}
/**
* 這里簡單實現(xiàn)刘离,通過隨機數(shù)生成工作ID室叉、數(shù)據(jù)ID
* 不生成重復id要通過datacenterId和workerId來做區(qū)分
*/
private static class SingletonClassInstance {
static Random random = new Random();
private static final IdWorker instance = new IdWorker(random.nextInt(31), random.nextInt(31), 1);
}
/**
* 單例調(diào)用入口
*/
public static IdWorker getInstance() {
return SingletonClassInstance.instance;
}
//---------------測試---------------
public static void main(String[] args) {
for (int i = 0; i < 30; i++) {
System.out.println(IdWorker.getInstance().nextId());
}
}
}
文章代碼參考自煲煲菜的博客
如有侵權(quán)之處請留言告知,會立即刪除硫惕。