Java收集的雪花算法代碼詳解
更新時間:2021年10月10日 16:47:29 作者:java265
這篇文章主要介紹了Java實現(xiàn)雪花算法的詳細代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
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; // 設(shè)置一個時間初始值 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)); } // 下面是說假設(shè)在同一個毫秒內(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ù)字,轉(zhuǎn)換成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()); } } }
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Java web實現(xiàn)賬號單一登錄,防止同一賬號重復(fù)登錄(踢人效果)
這篇文章主要介紹了Java web實現(xiàn)賬號單一登錄,防止同一賬號重復(fù)登錄,有點類似于qq登錄踢人效果,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10SpringBoot使用Graylog日志收集的實現(xiàn)示例
Graylog是一個生產(chǎn)級別的日志收集系統(tǒng),集成Mongo和Elasticsearch進行日志收集,這篇文章主要介紹了SpringBoot使用Graylog日志收集的實現(xiàn)示例,感興趣的小伙伴們可以參考一下2019-04-04Fluent Mybatis如何做到代碼邏輯和sql邏輯的合一
對比原生Mybatis, Mybatis Plus或者其他框架,F(xiàn)luentMybatis提供了哪些便利呢?很多朋友對這一問題不是很清楚,今天小編給大家?guī)硪黄坛剃P(guān)于Fluent Mybatis如何做到代碼邏輯和sql邏輯的合一,一起看看吧2021-08-08MyBatis-Plus 主鍵生成策略的幾種實現(xiàn)方式
主鍵生成策略是指在數(shù)據(jù)庫中為每條記錄生成唯一標識符的方法,本文就來介紹一下MyBatis-Plus 主鍵生成策略的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-05-05詳解關(guān)于Windows10 Java環(huán)境變量配置問題的解決辦法
這篇文章主要介紹了關(guān)于Windows10 Java環(huán)境變量配置問題的解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03mapstruct的用法之qualifiedByName示例詳解
qualifiedByName的意思就是使用這個Mapper接口中的指定的默認方法去處理這個屬性的轉(zhuǎn)換,而不是簡單的get?set,今天通過本文給大家介紹下mapstruct的用法之qualifiedByName示例詳解,感興趣的朋友一起看看吧2022-04-04如何在SpringBoot項目中集成SpringSecurity進行權(quán)限管理
在本文中,我們將討論如何在Spring?Boot項目中集成權(quán)限管理,我們將使用Spring?Security框架,這是一個專門用于實現(xiàn)安全性功能的框架,包括認證和授權(quán),需要的朋友可以參考下2023-07-07Java使用正則表達式截取重復(fù)出現(xiàn)的XML字符串功能示例
這篇文章主要介紹了Java使用正則表達式截取重復(fù)出現(xiàn)的XML字符串功能,涉及java針對xml字符串及指定格式字符串的正則匹配相關(guān)操作技巧,需要的朋友可以參考下2017-08-08