天天看點

分庫分表之後,id主鍵如何處理?

(1)資料庫自增id

這個就是說你的系統裡每次得到一個id,都是往一個庫的一個表裡插入一條沒什麼業務含義的資料,然後擷取一個資料庫自增的一個id。拿到這個id之後再往對應的分庫分表裡去寫入。

這個方案的好處就是友善簡單,誰都會用;缺點就是單庫生成自增id,要是高并發的話,就會有瓶頸的;如果你硬是要改進一下,那麼就專門開一個服務出來,這個服務每次就拿到目前id最大值,然後自己遞增幾個id,一次性傳回一批id,然後再把目前最大id值修改成遞增幾個id之後的一個值;但是無論怎麼說都是基于單個資料庫。

适合的場景:你分庫分表就倆原因,要不就是單庫并發太高,要不就是單庫資料量太大;除非是你并發不高,但是資料量太大導緻的分庫分表擴容,你可以用這個方案,因為可能每秒最高并發最多就幾百,那麼就走單獨的一個庫和表生成自增主鍵即可。

(2)uuid

好處就是本地生成,不要基于資料庫來了;不好之處就是,uuid太長了,作為主鍵性能太差了,不适合用于主鍵。

适合的場景:如果你是要随機生成個什麼檔案名了,編号之類的,你可以用uuid,但是作為主鍵是不能用uuid的。

UUID.randomUUID().toString().replace(“-”, “”) -> sfsdf23423rr234sfdaf
           

(3)擷取系統目前時間

這個就是擷取目前時間即可,但是問題是,并發很高的時候,比如一秒并發幾千,會有重複的情況,這個是肯定不合适的。基本就不用考慮了。

适合的場景:一般如果用這個方案,是将目前時間跟很多其他的業務字段拼接起來,作為一個id,如果業務上你覺得可以接受,那麼也是可以的。你可以将别的業務字段值跟目前時間拼接起來,組成一個全局唯一的編号,訂單編号,時間戳 + 使用者id + 業務含義編碼

(4)snowflake算法

twitter開源的分布式id生成算法,就是把一個64位的long型的id,1個bit是不用的,用其中的41 bit作為毫秒數,用10 bit作為工作機器id,12 bit作為序列号

  • 1 bit:不用,為啥呢?因為二進制裡第一個bit為如果是1,那麼都是負數,但是我們生成的id都是正數,是以第一個bit統一都是0
  • 41 bit:表示的是時間戳,機關是毫秒。41 bit可以表示的數字多達2^41 - 1,也就是可以辨別2 ^ 41 - 1個毫秒值,換算成年就是表示69年的時間。
  • 10 bit:記錄工作機器id,代表的是這個服務最多可以部署在2^10台機器上哪,也就是1024台機器。但是10 bit裡5個bit代表機房id,5個bit代表機器id。意思就是最多代表2 ^ 5個機房(32個機房),每個機房裡可以代表2 ^ 5個機器(32台機器)。
  • 12 bit:這個是用來記錄同一個毫秒内産生的不同id,12 bit可以代表的最大正整數是2 ^ 12 - 1 = 4096,也就是說可以用這個12bit代表的數字來區分同一個毫秒内的4096個不同的id
0 | 0001100 10100010 10111110 10001001 01011100 00 | 10001 | 1 1001 | 0000 00000000
           
public class IdWorker {

    private long workerId;
    private long datacenterId;
    private long sequence;

    public IdWorker(long workerId, long datacenterId, long sequence) {
        // sanity check for workerId
        // 這兒不就檢查了一下,要求就是你傳遞進來的機房id和機器id不能超過32,不能小于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));
        }
        System.out.printf(
                "worker starting. timestamp left shift %d, datacenter id bits %d, worker id bits %d, sequence bits %d, workerid %d",
                timestampLeftShift, datacenterIdBits, workerIdBits, sequenceBits, workerId);

        this.workerId = workerId;
        this.datacenterId = datacenterId;
        this.sequence = sequence;
    }

    private long twepoch = 1288834974657L;

    private long workerIdBits = 5L;
    private long datacenterIdBits = 5L;

    // 這個是二進制運算,就是 5 bit最多隻能有31個數字,也就是說機器id最多隻能是32以内
    private long maxWorkerId = -1L ^ (-1L << workerIdBits);

    // 這個是一個意思,就是 5 bit最多隻能有31個數字,機房id最多隻能是32以内
    private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
    private long sequenceBits = 12L;

    private long workerIdShift = sequenceBits;
    private long datacenterIdShift = sequenceBits + workerIdBits;
    private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
    private long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long lastTimestamp = -1L;

    public long getWorkerId() {
        return workerId;
    }

    public long getDatacenterId() {
        return datacenterId;
    }

    public long getTimestamp() {
        return System.currentTimeMillis();
    }

    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));
        }

        if (lastTimestamp == timestamp) {
            // 這個意思是說一個毫秒内最多隻能有4096個數字
            // 無論你傳遞多少進來,這個位運算保證始終就是在4096這個範圍内,避免你自己傳遞個sequence超過了4096這個範圍
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }

        // 這兒記錄一下最近一次生成id的時間戳,機關是毫秒
        lastTimestamp = timestamp;

        // 這兒就是将時間戳左移,放到 41 bit那兒;
        // 将機房 id左移放到 5 bit那兒;
        // 将機器id左移放到5 bit那兒;将序号放最後12 bit;
        // 最後拼接起來成一個 64 bit的二進制數字,轉換成 10 進制就是個 long 型
        return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift)
                | (workerId << workerIdShift) | sequence;
    }

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

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

    // ---------------測試---------------
    public static void main(String[] args) {
        IdWorker worker = new IdWorker(1, 1, 1);
        for (int i = 0; i < 30; i++) {
            System.out.println(worker.nextId());
        }
    }

}
           

怎麼說呢,大概這個意思吧,就是說41 bit,就是目前毫秒機關的一個時間戳,就這意思;然後5 bit是你傳遞進來的一個機房id(但是最大隻能是32以内),5 bit是你傳遞進來的機器id(但是最大隻能是32以内),剩下的那個10 bit序列号,就是如果跟你上次生成id的時間還在一個毫秒内,那麼會把順序給你累加,最多在4096個序号以内。

是以你自己利用這個工具類,自己搞一個服務,然後對每個機房的每個機器都初始化這麼一個東西,剛開始這個機房的這個機器的序号就是0。然後每次接收到一個請求,說這個機房的這個機器要生成一個id,你就找到對應的Worker生成。

利用這個snowflake算法,你可以開發自己公司的服務,甚至對于機房id和機器id,反正給你預留了5 bit + 5 bit,你換成别的有業務含義的東西也可以的。

這個snowflake算法相對來說還是比較靠譜的,是以你要真是搞分布式id生成,如果是高并發啥的,那麼用這個應該性能比較好,一般每秒幾萬并發的場景,也足夠你用了。

繼續閱讀