Java中的snowflake算法詳解
snowflake 算法
SnowFlake算法的優(yōu)點:
- 生成ID時不依賴于DB,完全在內(nèi)存生成,高性能高可用。
- ID呈趨勢遞增,后續(xù)插入索引樹的時候性能較好。
SnowFlake算法的缺點:
- 依賴于系統(tǒng)時鐘的一致性。如果某臺機(jī)器的系統(tǒng)時鐘回?fù)埽锌赡茉斐蒊D沖突,或者ID亂序。
snowflake 算法是 twitter 開源的分布式 id 生成算法,采用 Scala 語言實現(xiàn),是把一個 64 位的 long 型的 id,1 個 bit 是不用的,用其中的 41 bits 作為毫秒數(shù),用 10 bits 作為工作機(jī)器 id,12 bits 作為序列號。
- 1 bit:不用,為啥呢?因為二進(jìn)制里第一個 bit 為如果是 1,那么都是負(fù)數(shù),但是我們生成的 id 都是正數(shù),所以第一個 bit 統(tǒng)一都是 0。
- 41 bits:表示的是時間戳,單位是毫秒。41 bits 可以表示的數(shù)字多達(dá) 2^41 - 1 ,也就是可以標(biāo)識 2^41 - 1 個毫秒值,換算成年就是表示 69 年的時間。
- 10 bits:記錄工作機(jī)器 id,代表的是這個服務(wù)最多可以部署在 2^10 臺機(jī)器上,也就是 1024 臺機(jī)器。但是 10 bits 里 5 個 bits 代表機(jī)房 id,5 個 bits 代表機(jī)器 id。意思就是最多代表 2^5 個機(jī)房(32 個機(jī)房),每個機(jī)房里可以代表 2^5 個機(jī)器(32 臺機(jī)器)。
- 12 bits:這個是用來記錄同一個毫秒內(nèi)產(chǎn)生的不同 id,12 bits 可以代表的最大正整數(shù)是 2^12 - 1 = 4096 ,也就是說可以用這個 12 bits 代表的數(shù)字來區(qū)分同一個毫秒內(nèi)的 4096 個不同的 id。
0 | 0001100 10100010 10111110 10001001 01011100 00 | 10001 | 1 1001 | 0000 00000000
public class IdWorker {
private long workerId;
private long datacenterId;
private long sequence;
public IdWorker(long workerId, long datacenterId, long sequence) {
// sanity check for workerId
// 這兒不就檢查了一下,要求就是你傳遞進(jìn)來的機(jī)房id和機(jī)器id不能超過32,不能小于0
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;
private long workerIdBits = 5L;
private long datacenterIdBits = 5L;
// 這個是二進(jìn)制運算,就是 5 bit最多只能有31個數(shù)字,也就是說機(jī)器id最多只能是32以內(nèi)
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 這個是一個意思,就是 5 bit最多只能有31個數(shù)字,機(jī)房id最多只能是32以內(nèi)
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private long sequenceBits = 12L;
private long workerIdShift = sequenceBits;
private long datacenterIdShift = sequenceBits + workerIdBits;
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private long sequenceMask = -1L ^ (-1L << sequenceBits);
private long lastTimestamp = -1L;
public long getWorkerId() {
return workerId;
}
public long getDatacenterId() {
return datacenterId;
}
public long getTimestamp() {
return System.currentTimeMillis();
}
public synchronized long nextId() {
// 這兒就是獲取當(dāng)前時間戳,單位是毫秒
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));
}
if (lastTimestamp == timestamp) {
// 這個意思是說一個毫秒內(nèi)最多只能有4096個數(shù)字
// 無論你傳遞多少進(jìn)來,這個位運算保證始終就是在4096這個范圍內(nèi),避免你自己傳遞個sequence超過了4096這個范圍
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
// 這兒記錄一下最近一次生成id的時間戳,單位是毫秒
lastTimestamp = timestamp;
// 這兒就是將時間戳左移,放到 41 bit那兒;
// 將機(jī)房 id左移放到 5 bit那兒;
// 將機(jī)器id左移放到5 bit那兒;將序號放最后12 bit;
// 最后拼接起來成一個 64 bit的二進(jìn)制數(shù)字,轉(zhuǎn)換成 10 進(jìn)制就是個 long 型
return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
}
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 < 30; i++) {
System.out.println(worker.nextId());
}
}
}怎么說呢,大概這個意思吧,就是說 41 bit 是當(dāng)前毫秒單位的一個時間戳,就這意思;然后 5 bit 是你傳遞進(jìn)來的一個機(jī)房 id(但是最大只能是 32 以內(nèi)),另外 5 bit 是你傳遞進(jìn)來的機(jī)器 id(但是最大只能是 32 以內(nèi)),剩下的那個 12 bit 序列號,就是如果跟你上次生成 id 的時間還在一個毫秒內(nèi),那么會把順序給你累加,最多在 4096 個序號以內(nèi)。
所以你自己利用這個工具類,自己搞一個服務(wù),然后對每個機(jī)房的每個機(jī)器都初始化這么一個東西,剛開始這個機(jī)房的這個機(jī)器的序號就是 0。然后每次接收到一個請求,說這個機(jī)房的這個機(jī)器要生成一個 id,你就找到對應(yīng)的 Worker 生成。
利用這個 snowflake 算法,你可以開發(fā)自己公司的服務(wù),甚至對于機(jī)房 id 和機(jī)器 id,反正給你預(yù)留了 5 bit + 5 bit,你換成別的有業(yè)務(wù)含義的東西也可以的。
這個 snowflake 算法相對來說還是比較靠譜的,所以你要真是搞分布式 id 生成,如果是高并發(fā)啥的,那么用這個應(yīng)該性能比較好,一般每秒幾萬并發(fā)的場景,也足夠你用了。
到此這篇關(guān)于Java中的snowflake算法詳解的文章就介紹到這了,更多相關(guān)snowflake算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring boot tomcat jdbc pool的屬性綁定
這篇文章主要介紹了spring boot tomcat jdbc pool的屬性綁定的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友參考下2018-01-01
Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計
本文主要介紹了Java中計算集合中元素的出現(xiàn)次數(shù)統(tǒng)計,使用Collections類配合HashMap來統(tǒng)計和java lamb 計算這兩種方式,具有一定的參考價值,感興趣可以了解一下2024-02-02
SpringBoot參數(shù)校驗之@Validated的使用詳解
這篇文章主要通過示例為大家詳細(xì)介紹一下介紹了SpringBoot參數(shù)校驗中@Validated的使用方法,文中的示例代碼講解詳細(xì),需要的可以參考一下2022-06-06
JAVA利用順序表實現(xiàn)“楊輝三角”的思路及代碼示例
楊輝三角形是中國古代數(shù)學(xué)的杰出研究成果之一,是我國北宋數(shù)學(xué)家賈憲于1050年首先發(fā)現(xiàn)并使用的,這篇文章主要介紹了JAVA利用順序表實現(xiàn)楊輝三角的思路及代碼示例,需要的朋友可以參考下2025-01-01
詳解如何在SpringBoot中優(yōu)雅地重試調(diào)用第三方API
在實際的應(yīng)用中,我們經(jīng)常需要調(diào)用第三方API來獲取數(shù)據(jù)或執(zhí)行某些操作,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12

