Java收集的雪花算法代碼詳解
更新時間:2021年10月10日 16:47:29 作者:java265
這篇文章主要介紹了Java實現(xiàn)雪花算法的詳細代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
package com.java265.other;
public class Test {
// 因為二進制里第一個 bit 為如果是 1,那么都是負數(shù),但是我們生成的 id 都是正數(shù),所以第一個 bit 統(tǒng)一都是 0。
// 機器ID 2進制5位 32位減掉1位 31個
private long workerId;
// 機房ID 2進制5位 32位減掉1位 31個
private long datacenterId;
// 代表一毫秒內(nèi)生成的多個id的最新序號 12位 4096 -1 = 4095 個
private long sequence;
// 設置一個時間初始值 2^41 - 1 差不多可以用69年
private long twepoch = 1585644268888L;
// 5位的機器id
private long workerIdBits = 5L;
// 5位的機房id
private long datacenterIdBits = 5L;
// 每毫秒內(nèi)產(chǎn)生的id數(shù) 2 的 12次方
private long sequenceBits = 12L;
// 這個是二進制運算,就是5 bit最多只能有31個數(shù)字,也就是說機器id最多只能是32以內(nèi)
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 這個是一個意思,就是5 bit最多只能有31個數(shù)字,機房id最多只能是32以內(nèi)
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private long workerIdShift = sequenceBits;
private long datacenterIdShift = sequenceBits + workerIdBits;
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private long sequenceMask = -1L ^ (-1L << sequenceBits);
// 記錄產(chǎn)生時間毫秒數(shù),判斷是否是同1毫秒
private long lastTimestamp = -1L;
public long getWorkerId() {
return workerId;
}
public long getDatacenterId() {
return datacenterId;
}
public long getTimestamp() {
return System.currentTimeMillis();
}
public Test(long workerId, long datacenterId, long sequence) {
// 檢查機房id和機器id是否超過31 不能小于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));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
}
// 這個是核心方法,通過調(diào)用nextId()方法,讓當前這臺機器上的snowflake算法程序生成一個全局唯一的id
public synchronized long nextId() {
// 這兒就是獲取當前時間戳,單位是毫秒
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));
}
// 下面是說假設在同一個毫秒內(nèi),又發(fā)送了一個請求生成一個id
// 這個時候就得把seqence序號給遞增1,最多就是4096
if (lastTimestamp == timestamp) {
// 這個意思是說一個毫秒內(nèi)最多只能有4096個數(shù)字,無論你傳遞多少進來,
// 這個位運算保證始終就是在4096這個范圍內(nèi),避免你自己傳遞個sequence超過了4096這個范圍
sequence = (sequence + 1) & sequenceMask;
// 當某一毫秒的時間,產(chǎn)生的id數(shù) 超過4095,系統(tǒng)會進入等待,直到下一毫秒,系統(tǒng)繼續(xù)產(chǎn)生ID
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
// 這兒記錄一下最近一次生成id的時間戳,單位是毫秒
lastTimestamp = timestamp;
// 這兒就是最核心的二進制位運算操作,生成一個64bit的id
// 先將當前時間戳左移,放到41 bit那兒;將機房id左移放到5 bit那兒;將機器id左移放到5 bit那兒;將序號放最后12 bit
// 最后拼接起來成一個64 bit的二進制數(shù)字,轉換成10進制就是個long型
return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
}
/**
* 當某一毫秒的時間,產(chǎn)生的id數(shù) 超過4095,系統(tǒng)會進入等待,直到下一毫秒,系統(tǒng)繼續(xù)產(chǎn)生ID
*
* @param lastTimestamp
* @return
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
// 獲取當前時間戳
private long timeGen() {
return System.currentTimeMillis();
}
/**
* main 測試類
*
* @param args
*/
public static void main(String[] args) {
System.out.println(1 & 4596);
System.out.println(2 & 4596);
System.out.println(6 & 4596);
System.out.println(6 & 4596);
System.out.println(6 & 4596);
System.out.println(6 & 4596);
Test test = new Test(1, 1, 1);
for (int i = 0; i < 22; i++) {
System.out.println(test.nextId());
}
}
}
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內(nèi)容!
相關文章
java ArrayList集合中的某個對象屬性進行排序的實現(xiàn)代碼
這篇文章主要介紹了java ArrayList集合中的某個對象屬性進行排序的實現(xiàn)代碼,需要的朋友可以參考下2016-07-07
Java中SynchronousQueue的底層實現(xiàn)原理剖析
BlockingQueue的實現(xiàn)類中,有一種阻塞隊列比較特殊,就是SynchronousQueue(同步移交隊列),隊列長度為0。本文就來剖析一下SynchronousQueue的底層實現(xiàn)原理,感興趣的可以了解一下2022-11-11
使用springboot logback動態(tài)獲取application的配置項
這篇文章主要介紹了使用springboot logback動態(tài)獲取application的配置項,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java實現(xiàn)定時讀取json文件里內(nèi)容的示例代碼
有時候我們會需要定時來讀取JSON配置文件里的內(nèi)容,來執(zhí)行一些業(yè)務邏輯上的操作,本文就介紹了Java實現(xiàn)定時讀取json文件里內(nèi)容的示例代碼,感興趣的可以了解一下2023-08-08

