工具類:
@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());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/266329.html
標籤:其他
下一篇:JAVA集合詳解(一)
