Java生成唯一id的幾種實(shí)現(xiàn)方式
1.數(shù)據(jù)庫(kù)自增序列方式
數(shù)據(jù)庫(kù)方式比較簡(jiǎn)單,比如oracle可以用序列生成id,Mysql中的AUTO_INCREMENT等,這樣可以生成唯一的ID,性能和穩(wěn)定性依賴(lài)于數(shù)據(jù)庫(kù)!如mysql主鍵遞增:
2.系統(tǒng)時(shí)間戳
這種方式每秒最多一千個(gè),如果是單體web系統(tǒng)集群部署方式,可以為每臺(tái)機(jī)器加個(gè)標(biāo)識(shí)?。úl(fā)量較大不建議使用)
/** * 根據(jù)時(shí)間戳生成唯一id */ @Test public void test(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSS"); String id = sdf.format(System.currentTimeMillis()); System.out.println("id:"+id); //id:202010221400070793 }
3.UUID
uuid生成全球唯一id,生成簡(jiǎn)單粗暴,本地生成,沒(méi)有網(wǎng)絡(luò)開(kāi)銷(xiāo),效率高;但是長(zhǎng)度較長(zhǎng)無(wú)規(guī)律,不易維護(hù)?。ú唤ㄗh作為數(shù)據(jù)庫(kù)主鍵)
/** * 用uuid生成為id */ @Test public void testUUID(){ String uuid = UUID.randomUUID().toString(); System.out.println("uuid:"+uuid); //uuid:49abc3f3-d6cc-4401-b24a-0fc808d1b594 }
4.雪花算法
SnowFlake算法生成id的結(jié)果是一個(gè)64bit大小的Long類(lèi)型,
本地生成,沒(méi)有網(wǎng)絡(luò)開(kāi)銷(xiāo),效率高,但是依賴(lài)機(jī)器時(shí)鐘
public class SnowflakeIdWorker { // ==============================Fields=========================================== /** 開(kāi)始時(shí)間截 (2015-01-01) */ private final long twepoch = 1420041600000L; /** 機(jī)器id所占的位數(shù) */ private final long workerIdBits = 5L; /** 數(shù)據(jù)標(biāo)識(shí)id所占的位數(shù) */ private final long datacenterIdBits = 5L; /** 支持的最大機(jī)器id,結(jié)果是31 (這個(gè)移位算法可以很快的計(jì)算出幾位二進(jìn)制數(shù)所能表示的最大十進(jìn)制數(shù)) */ private final long maxWorkerId = -1L ^ (-1L << workerIdBits); /** 支持的最大數(shù)據(jù)標(biāo)識(shí)id,結(jié)果是31 */ private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); /** 序列在id中占的位數(shù) */ private final long sequenceBits = 12L; /** 機(jī)器ID向左移12位 */ private final long workerIdShift = sequenceBits; /** 數(shù)據(jù)標(biāo)識(shí)id向左移17位(12+5) */ private final long datacenterIdShift = sequenceBits + workerIdBits; /** 時(shí)間截向左移22位(5+5+12) */ private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; /** 生成序列的掩碼,這里為4095 (0b111111111111=0xfff=4095) */ private final long sequenceMask = -1L ^ (-1L << sequenceBits); /** 工作機(jī)器ID(0~31) */ private long workerId; /** 數(shù)據(jù)中心ID(0~31) */ private long datacenterId; /** 毫秒內(nèi)序列(0~4095) */ private long sequence = 0L; /** 上次生成ID的時(shí)間截 */ private long lastTimestamp = -1L; //==============================Constructors===================================== /** * 構(gòu)造函數(shù) * @param workerId 工作ID (0~31) * @param datacenterId 數(shù)據(jù)中心ID (0~31) */ public SnowflakeIdWorker(long workerId, long datacenterId) { 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; } // ==============================Methods========================================== /** * 獲得下一個(gè)ID (該方法是線程安全的) * @return SnowflakeId */ public synchronized long nextId() { long timestamp = timeGen(); //如果當(dāng)前時(shí)間小于上一次ID生成的時(shí)間戳,說(shuō)明系統(tǒng)時(shí)鐘回退過(guò)這個(gè)時(shí)候應(yīng)當(dāng)拋出異常 if (timestamp < lastTimestamp) { throw new RuntimeException( String.format ("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } //如果是同一時(shí)間生成的,則進(jìn)行毫秒內(nèi)序列 if (lastTimestamp == timestamp) { sequence = (sequence + 1) & sequenceMask; //毫秒內(nèi)序列溢出 if (sequence == 0) { //阻塞到下一個(gè)毫秒,獲得新的時(shí)間戳 timestamp = tilNextMillis(lastTimestamp); } } //時(shí)間戳改變,毫秒內(nèi)序列重置 else { sequence = 0L; } //上次生成ID的時(shí)間截 lastTimestamp = timestamp; //移位并通過(guò)或運(yùn)算拼到一起組成64位的ID return ((timestamp - twepoch) << timestampLeftShift) // | (datacenterId << datacenterIdShift) // | (workerId << workerIdShift) // | sequence; } /** * 阻塞到下一個(gè)毫秒,直到獲得新的時(shí)間戳 * @param lastTimestamp 上次生成ID的時(shí)間截 * @return 當(dāng)前時(shí)間戳 */ protected long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 返回以毫秒為單位的當(dāng)前時(shí)間 * @return 當(dāng)前時(shí)間(毫秒) */ protected long timeGen() { return System.currentTimeMillis(); } //==============================Test============================================= /** 測(cè)試 */ public static void main(String[] args) { SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0); long id = idWorker.nextId(); System.out.println("id:"+id); //id:768842202204864512 } }
5.Redis生成全局唯一id
基于redis單線程的原子性特點(diǎn)生成全局唯一id,redis性能高,支持集群分片,唯一缺點(diǎn)就是依賴(lài)redis服務(wù)(推薦使用)
實(shí)現(xiàn)過(guò)程(核心代碼):
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.Calendar; import java.util.Date; /** * @author xf * @version 1.0.0 * @ClassName PrimaryKeyUtil * @Description TODO 利用redis生成數(shù)據(jù)庫(kù)全局唯一性id * @createTime 2020.10.22 10:42 */ @Service public class PrimaryKeyUtil { @Autowired private RedisTemplate redisTemplate; /** * 獲取年的后兩位加上一年多少天+當(dāng)前小時(shí)數(shù)作為前綴 * @param date * @return */ public String getOrderIdPrefix(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); //String.format("%1$02d", var) // %后的1指第一個(gè)參數(shù),當(dāng)前只有var一個(gè)可變參數(shù),所以就是指var。 // $后的0表示,位數(shù)不夠用0補(bǔ)齊,如果沒(méi)有這個(gè)0(如%1$nd)就以空格補(bǔ)齊,0后面的n表示總長(zhǎng)度,總長(zhǎng)度可以可以是大于9例如(%1$010d),d表示將var按十進(jìn)制轉(zhuǎn)字符串,長(zhǎng)度不夠的話(huà)用0或空格補(bǔ)齊。 String monthFormat = String.format("%1$02d", month+1); String dayFormat = String.format("%1$02d", day); String hourFormat = String.format("%1$02d", hour); return year + monthFormat + dayFormat+hourFormat; } /** * 生成訂單號(hào) * @param prefix * @return */ public Long orderId(String prefix) { String key = "ORDER_ID_" + prefix; String orderId = null; try { Long increment = redisTemplate.opsForValue().increment(key,1); //往前補(bǔ)6位 orderId=prefix+String.format("%1$06d",increment); } catch (Exception e) { System.out.println("生成單號(hào)失敗"); e.printStackTrace(); } return Long.valueOf(orderId); } }
測(cè)試redis生成唯一id,生成1000耗時(shí)514毫秒
import com.king.science.util.PrimaryKeyUtil; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.Date; /** * 測(cè)試類(lèi) */ @SpringBootTest class ScienceApplicationTests { @Autowired private PrimaryKeyUtil primaryKeyUtil; /** * 使用redis生成唯一id */ @Test public void testRedis() { long startMillis = System.currentTimeMillis(); String orderIdPrefix = primaryKeyUtil.getOrderIdPrefix(new Date()); //生成單個(gè)id //Long aLong = primaryKeyUtil.orderId(orderIdPrefix); for (int i = 0; i < 1000; i++) { Long aLong = primaryKeyUtil.orderId(orderIdPrefix); System.out.println(aLong); } long endMillis = System.currentTimeMillis(); System.out.println("測(cè)試生成1000個(gè)使用時(shí)間:"+(endMillis-startMillis)+",單位毫秒"); //測(cè)試生成1000個(gè)使用時(shí)間:514,單位毫秒 } }
redis共incr1000次
如上就是本次總結(jié)的五種生成唯一id的方式,你們項(xiàng)目中使用的什么方式呢?
到此這篇關(guān)于Java生成唯一id的幾種實(shí)現(xiàn)方式 的文章就介紹到這了,更多相關(guān)Java生成唯一id內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java控制臺(tái)實(shí)現(xiàn)學(xué)生信息管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java控制臺(tái)實(shí)現(xiàn)學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02使用Spring源碼報(bào)錯(cuò)java:找不到類(lèi) InstrumentationSavingAgent的問(wèn)題
這篇文章主要介紹了使用Spring源碼報(bào)錯(cuò)java:找不到類(lèi) InstrumentationSavingAgent的問(wèn)題,本文給大家分享解決方法,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10java實(shí)現(xiàn)的海盜算法優(yōu)化版
這篇文章主要介紹了java實(shí)現(xiàn)的海盜算法優(yōu)化版,結(jié)合實(shí)例形式分析了java海盜算法的具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-07-07SpringBoot啟動(dòng)時(shí)自動(dòng)執(zhí)行指定方法的幾種實(shí)現(xiàn)方式
在Spring Boot應(yīng)用程序中,要實(shí)現(xiàn)在應(yīng)用啟動(dòng)時(shí)自動(dòng)執(zhí)行某些代碼,本文主要介紹了SpringBoot啟動(dòng)時(shí)自動(dòng)執(zhí)行指定方法的幾種方式,文中有相關(guān)的代碼示例供大家參考,需要的朋友可以參考下2024-03-03Spring?boot?easyexcel?實(shí)現(xiàn)復(fù)合數(shù)據(jù)導(dǎo)出、按模塊導(dǎo)出功能
這篇文章主要介紹了Spring?boot?easyexcel?實(shí)現(xiàn)復(fù)合數(shù)據(jù)導(dǎo)出、按模塊導(dǎo)出,實(shí)現(xiàn)思路流程是準(zhǔn)備一個(gè)導(dǎo)出基礎(chǔ)填充模板,默認(rèn)填充key,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09JAVA中使用JSON進(jìn)行數(shù)據(jù)傳遞示例
本篇文章主要介紹了JAVA中使用JSON進(jìn)行數(shù)據(jù)傳遞示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-01-01Mybatis-Plus使用ID_WORKER生成主鍵id重復(fù)的解決方法
本文主要介紹了Mybatis-Plus使用ID_WORKER生成主鍵id重復(fù)的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07mybatis關(guān)系映射之一對(duì)多和多對(duì)一
今天小編就為大家分享一篇關(guān)于mybatis關(guān)系映射之一對(duì)多和多對(duì)一,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2019-01-01