欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java生成唯一id的幾種實現(xiàn)方式

 更新時間:2024年01月22日 15:42:26   作者:余生一個帆  
本文主要介紹了Java生成唯一id的幾種實現(xiàn)方式,主要介紹了5種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

1.數(shù)據(jù)庫自增序列方式

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

2.系統(tǒng)時間戳

這種方式每秒最多一千個,如果是單體web系統(tǒng)集群部署方式,可以為每臺機(jī)器加個標(biāo)識?。úl(fā)量較大不建議使用)

   /**
     * 根據(jù)時間戳生成唯一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é)果是一個64bit大小的Long類型,
本地生成,沒有網(wǎng)絡(luò)開銷,效率高,但是依賴機(jī)器時鐘

public class SnowflakeIdWorker {

    // ==============================Fields===========================================
    /** 開始時間截 (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 (這個移位算法可以很快的計算出幾位二進(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;

    /** 時間截向左移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的時間截 */
    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==========================================
    /**
     * 獲得下一個ID (該方法是線程安全的)
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        //如果當(dāng)前時間小于上一次ID生成的時間戳,說明系統(tǒng)時鐘回退過這個時候應(yīng)當(dāng)拋出異常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format
                    ("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一時間生成的,則進(jìn)行毫秒內(nèi)序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            //毫秒內(nèi)序列溢出
            if (sequence == 0) {
                //阻塞到下一個毫秒,獲得新的時間戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //時間戳改變,毫秒內(nèi)序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的時間截
        lastTimestamp = timestamp;

        //移位并通過或運算拼到一起組成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) //
                | (datacenterId << datacenterIdShift) //
                | (workerId << workerIdShift) //
                | sequence;
    }

    /**
     * 阻塞到下一個毫秒,直到獲得新的時間戳
     * @param lastTimestamp 上次生成ID的時間截
     * @return 當(dāng)前時間戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒為單位的當(dāng)前時間
     * @return 當(dāng)前時間(毫秒)
     */
    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單線程的原子性特點生成全局唯一id,redis性能高,支持集群分片,唯一缺點就是依賴redis服務(wù)(推薦使用)
實現(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ù)作為前綴
     * @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指第一個參數(shù),當(dāng)前只有var一個可變參數(shù),所以就是指var。
        // $后的0表示,位數(shù)不夠用0補(bǔ)齊,如果沒有這個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耗時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());
        //生成單個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個使用時間:"+(endMillis-startMillis)+",單位毫秒");
        //測試生成1000個使用時間:514,單位毫秒
    }

}

redis共incr1000次

如上就是本次總結(jié)的五種生成唯一id的方式,你們項目中使用的什么方式呢?

到此這篇關(guān)于Java生成唯一id的幾種實現(xiàn)方式 的文章就介紹到這了,更多相關(guān)Java生成唯一id內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論