分布式系統(tǒng)為什么不用自增id,要用雪花算法生成id???

分布式id創(chuàng)建的業(yè)務(wù)需求

? ? ? ?1.全局唯一性:不能出現(xiàn)重復(fù)的ID號,既然是唯一標(biāo)識,這是最基本的要求。
? ? ? ?2.趨勢遞增:在MySQL InnoDB引擎中使用的是聚集索引,由于多數(shù)RDBMS使用B-tree的數(shù)據(jù)結(jié)構(gòu)來存儲索引數(shù)據(jù),在主鍵的選擇上面我們應(yīng)該盡量使用有序的主鍵保證寫入性能。
? ? ? ?3.單調(diào)遞增:保證下一個ID一定大于上一個ID,例如事務(wù)版本號、IM增量消息、排序等特殊需求。
? ? ? ?4.信息安全:如果ID是連續(xù)的,惡意用戶的扒取工作就非常容易做了,直接按照順序下載指定URL即可;如果是訂單號就更危險了,競對可以直接知道我們一天的單量。所以在一些應(yīng)用場景下,會需要ID無規(guī)則、不規(guī)則。
? ? ? ?5.分布式id里面最好包含時間戳,這樣就能夠在開發(fā)中快速了解這個分布式id的生成時間

為什么數(shù)據(jù)庫id自增不適合分布式id
  • id自增:當(dāng)數(shù)據(jù)量龐大時,在數(shù)據(jù)庫分庫分表后,數(shù)據(jù)庫自增id不能滿足唯一id來標(biāo)識數(shù)據(jù);因為每個表都按自己節(jié)奏自增,會造成id沖突,無法滿足需求。
    分庫分表:分表就是把一個表的數(shù)據(jù)放到多個表中,將一個庫的數(shù)據(jù)拆分到多個庫中

分布式ID的解決方案

1.uuid

  • 優(yōu)點:簡單,方便,性能好,全球唯一
  • 缺點:無序性,存儲的是字符串,查詢效率低,傳輸數(shù)據(jù)量大

2. Redis

???利用于Redis是單線程,所以也可以用生成全局唯一的ID??梢杂肦edis的原子操作 INCR和INCRBY來實現(xiàn)

  • 優(yōu)點:不依賴于數(shù)據(jù)庫,靈活方便 數(shù)字ID天然排序,對分頁,排序方便
  • 缺點:復(fù)雜度大,性能不好

3.snowflake(雪花算法)

????snowflake是Twitter開源的分布式ID生成算法,結(jié)果是一個long型的64bitID。其核心思想是:使用41bit作為毫秒數(shù),10bit作為機器的ID(5個bit是數(shù)據(jù)中心,5個bit的機器ID),12bit作為毫秒內(nèi)的流水號(意味著每個節(jié)點在每毫秒可以產(chǎn)生 4096 個 ID),最后還有一個符號位,永遠(yuǎn)是0

SnowFlake算法的優(yōu)點:

(1)生成ID時不依賴于數(shù)據(jù)庫,完全在內(nèi)存生成,高性能高可用。
(2)容量大,每秒可生成幾百萬ID。
(3)ID呈趨勢遞增,后續(xù)插入數(shù)據(jù)庫的索引樹的時候,性能較高。

SnowFlake算法的缺點:

(1)依賴于系統(tǒng)時鐘的一致性。如果某臺機器的系統(tǒng)時鐘回?fù)埽锌赡茉斐蒊D沖突,或者ID亂序。
(2)還有,在啟動之前,如果這臺機器的系統(tǒng)時間回?fù)苓^,那么有可能出現(xiàn)ID重復(fù)的危險。
工具類IdWorker

使用工具類的步驟(每次的id都是不一樣的,而且會有排序):
IdWorker idWorker=new IdWorker(1,1);
        for(int i=0;i<10000;i++){    
         long id = idWorker.nextId();  
           System.out.println(id);   
      }
工具類源碼
/**
 * <p>名稱:IdWorker.java</p>
 * <p>描述:分布式自增長ID</p>
 * <pre>
 *     Twitter的 Snowflake JAVA實現(xiàn)方案
 * </pre>
 * 核心代碼為其IdWorker這個類實現(xiàn),其原理結(jié)構(gòu)如下,我分別用一個0表示一位,用—分割開部分的作用:
 * 1||0---0000000000 0000000000 0000000000 0000000000 0 --- 00000 ---00000 ---000000000000
 * 在上面的字符串中,第一位為未使用(實際上也可作為long的符號位),接下來的41位為毫秒級時間,
 * 然后5位datacenter標(biāo)識位,5位機器ID(并不算標(biāo)識符,實際是為線程標(biāo)識),
 * 然后12位該毫秒內(nèi)的當(dāng)前毫秒內(nèi)的計數(shù),加起來剛好64位,為一個Long型。
 * 這樣的好處是,整體上按照時間自增排序,并且整個分布式系統(tǒng)內(nèi)不會產(chǎn)生ID碰撞(由datacenter和機器ID作區(qū)分),
 * 并且效率較高,經(jīng)測試,snowflake每秒能夠產(chǎn)生26萬ID左右,完全滿足需要。
 * <p>
 * 64位ID (42(毫秒)+5(機器ID)+5(業(yè)務(wù)編碼)+12(重復(fù)累加))
 *
 * @author Polim
 */
public class IdWorker {
    // 時間起始標(biāo)記點,作為基準(zhǔn),一般取系統(tǒng)的最近時間(一旦確定不能變動)
    private final static long twepoch = 1288834974657L;
    // 機器標(biāo)識位數(shù)
    private final static long workerIdBits = 5L;
    // 數(shù)據(jù)中心標(biāo)識位數(shù)
    private final static long datacenterIdBits = 5L;
    // 機器ID最大值
    private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 數(shù)據(jù)中心ID最大值
    private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    // 毫秒內(nèi)自增位
    private final static long sequenceBits = 12L;
    // 機器ID偏左移12位
    private final static long workerIdShift = sequenceBits;
    // 數(shù)據(jù)中心ID左移17位
    private final static long datacenterIdShift = sequenceBits + workerIdBits;
    // 時間毫秒左移22位
    private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
    /* 上次生產(chǎn)id時間戳 */
    private static long lastTimestamp = -1L;
    // 0,并發(fā)控制
    private long sequence = 0L;

    private final long workerId;
    // 數(shù)據(jù)標(biāo)識id部分
    private final long datacenterId;

    public IdWorker(){
        this.datacenterId = getDatacenterId(maxDatacenterId);
        this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
    }
    /**
     * @param workerId
     *            工作機器ID
     * @param datacenterId
     *            序列號
     */
    public IdWorker(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;
    }
    /**
     * 獲取下一個ID
     *
     * @return
     */
    public synchronized long nextId() {
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        if (lastTimestamp == timestamp) {
            // 當(dāng)前毫秒內(nèi),則+1
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                // 當(dāng)前毫秒內(nèi)計數(shù)滿了,則等待下一秒
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        // ID偏移組合生成最終的ID,并返回ID
        long nextId = ((timestamp - twepoch) << timestampLeftShift)
                | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift) | sequence;

        return nextId;
    }

    private long tilNextMillis(final long lastTimestamp) {
        long timestamp = this.timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = this.timeGen();
        }
        return timestamp;
    }

    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * <p>
     * 獲取 maxWorkerId
     * </p>
     */
    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuffer mpid = new StringBuffer();
        mpid.append(datacenterId);
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (!name.isEmpty()) {
            /*
             * GET jvmPid
             */
            mpid.append(name.split("@")[0]);
        }
        /*
         * MAC + PID 的 hashcode 獲取16個低位
         */
        return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    /**
     * <p>
     * 數(shù)據(jù)標(biāo)識id部分
     * </p>
     */
    protected static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            if (network == null) {
                id = 1L;
            } else {
                byte[] mac = network.getHardwareAddress();
                id = ((0x000000FF & (long) mac[mac.length - 1])
                        | (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
                id = id % (maxDatacenterId + 1);
            }
        } catch (Exception e) {
            System.out.println(" getDatacenterId: " + e.getMessage());
        }
        return id;
    }


    public static void main(String[] args) {

        IdWorker idWorker=new IdWorker(0,0);

        for(int i=0;i<10000;i++){
            long nextId = idWorker.nextId();
            System.out.println(nextId);
        }
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容