Java生成唯一id的幾種實(shí)現(xiàn)方式
1.數(shù)據(jù)庫自增序列方式
數(shù)據(jù)庫方式比較簡單,比如oracle可以用序列生成id,Mysql中的AUTO_INCREMENT等,這樣可以生成唯一的ID,性能和穩(wěn)定性依賴于數(shù)據(jù)庫!如mysql主鍵遞增:

2.系統(tǒng)時(shí)間戳
這種方式每秒最多一千個(gè),如果是單體web系統(tǒng)集群部署方式,可以為每臺機(jī)器加個(gè)標(biāo)識?。ú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,生成簡單粗暴,本地生成,沒有網(wǎng)絡(luò)開銷,效率高;但是長度較長無規(guī)律,不易維護(hù)?。ú唤ㄗh作為數(shù)據(jù)庫主鍵)
/**
* 用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類型,
本地生成,沒有網(wǎng)絡(luò)開銷,效率高,但是依賴機(jī)器時(shí)鐘
public class SnowflakeIdWorker {
// ==============================Fields===========================================
/** 開始時(shí)間截 (2015-01-01) */
private final long twepoch = 1420041600000L;
/** 機(jī)器id所占的位數(shù) */
private final long workerIdBits = 5L;
/** 數(shù)據(jù)標(biāo)識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)識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)識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í)間戳,說明系統(tǒng)時(shí)鐘回退過這個(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;
//移位并通過或運(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=============================================
/** 測試 */
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)就是依賴redis服務(wù)(推薦使用)
實(shí)現(xiàn)過程(核心代碼):
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ù)庫全局唯一性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ǔ)齊,如果沒有這個(gè)0(如%1$nd)就以空格補(bǔ)齊,0后面的n表示總長度,總長度可以可以是大于9例如(%1$010d),d表示將var按十進(jìn)制轉(zhuǎn)字符串,長度不夠的話用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;
}
/**
* 生成訂單號
* @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("生成單號失敗");
e.printStackTrace();
}
return Long.valueOf(orderId);
}
}
測試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;
/**
* 測試類
*/
@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("測試生成1000個(gè)使用時(shí)間:"+(endMillis-startMillis)+",單位毫秒");
//測試生成1000個(gè)使用時(shí)間:514,單位毫秒
}
}

redis共incr1000次

如上就是本次總結(jié)的五種生成唯一id的方式,你們項(xiàng)目中使用的什么方式呢?
到此這篇關(guān)于Java生成唯一id的幾種實(shí)現(xiàn)方式 的文章就介紹到這了,更多相關(guān)Java生成唯一id內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java與Python之間使用jython工具類實(shí)現(xiàn)數(shù)據(jù)交互
今天小編就為大家分享一篇關(guān)于Java與Python之間使用jython工具類實(shí)現(xiàn)數(shù)據(jù)交互,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-03-03
SpringBoot沒有讀取到application.yml問題及解決
這篇文章主要介紹了SpringBoot沒有讀取到application.yml問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
Java WebService 簡單實(shí)例(附實(shí)例代碼)
本篇文章主要介紹了Java WebService 簡單實(shí)例(附實(shí)例代碼), Web Service 是一種新的web應(yīng)用程序分支,他們是自包含、自描述、模塊化的應(yīng)用,可以發(fā)布、定位、通過web調(diào)用。有興趣的可以了解一下2017-01-01
Java分頁簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)介紹了Java分頁簡介的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-08-08
Java如何獲取一個(gè)IP段內(nèi)的所有IP地址
這篇文章主要為大家詳細(xì)介紹了Java如何根據(jù)起始和結(jié)束的IP地址獲取IP段內(nèi)所有IP地址,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
java時(shí)間戳轉(zhuǎn)日期格式的實(shí)現(xiàn)代碼
本篇文章是對java時(shí)間戳轉(zhuǎn)日期格式的實(shí)現(xiàn)代碼進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06

