mysql snowflake_一篇文章彻底搞懂snowflake算法及百度美团的最佳实践
寫在前面的話
一提到分布式ID自動生成方案,大家肯定都非常熟悉,并且立即能說出自家拿手的幾種方案,確實(shí),ID作為系統(tǒng)數(shù)據(jù)的重要標(biāo)識,重要性不言而喻,而各種方案也是歷經(jīng)多代優(yōu)化,請允許我用這個視角對分布式ID自動生成方案進(jìn)行分類:
實(shí)現(xiàn)方式
完全依賴數(shù)據(jù)源方式
ID的生成規(guī)則,讀取控制完全由數(shù)據(jù)源控制,常見的如數(shù)據(jù)庫的自增長ID,序列號等,或Redis的INCR/INCRBY原子操作產(chǎn)生順序號等。
半依賴數(shù)據(jù)源方式
ID的生成規(guī)則,有部分生成因子需要由數(shù)據(jù)源(或配置信息)控制,如snowflake算法。
不依賴數(shù)據(jù)源方式
ID的生成規(guī)則完全由機(jī)器信息獨(dú)立計算,不依賴任何配置信息和數(shù)據(jù)記錄,如常見的UUID,GUID等
實(shí)踐方案
實(shí)踐方案適用于以上提及的三種實(shí)現(xiàn)方式,可作為這三種實(shí)現(xiàn)方式的一種補(bǔ)充,旨在提升系統(tǒng)吞吐量,但原有實(shí)現(xiàn)方式的局限性依然存在。
實(shí)時獲取方案
顧名思義,每次要獲取ID時,實(shí)時生成。
簡單快捷,ID都是連續(xù)不間斷的,但吞吐量可能不是最高。
預(yù)生成方案
預(yù)先生成一批ID放在數(shù)據(jù)池里,可簡單自增長生成,也可以設(shè)置步長,分批生成,需要將這些預(yù)先生成的數(shù)據(jù),放在存儲容器里(JVM內(nèi)存,Redis,數(shù)據(jù)庫表均可)。
可以較大幅度地提升吞吐量,但需要開辟臨時存儲空間,斷電宕機(jī)后可能會丟失已有ID,ID可能有間斷。
方案簡介
以下對目前流行的分布式ID方案做簡單介紹
數(shù)據(jù)庫自增長ID
屬于完全依賴數(shù)據(jù)源的方式,所有的ID存儲在數(shù)據(jù)庫里,是最常用的ID生成辦法,在單體應(yīng)用時期得到了最廣泛的使用,建立數(shù)據(jù)表時利用數(shù)據(jù)庫自帶的auto_increment作主鍵,或是使用序列完成其他場景的一些自增長ID的需求。
優(yōu)點(diǎn):非常簡單,有序遞增,方便分頁和排序。
缺點(diǎn):分庫分表后,同一數(shù)據(jù)表的自增ID容易重復(fù),無法直接使用(可以設(shè)置步長,但局限性很明顯);性能吞吐量整個較低,如果設(shè)計一個單獨(dú)的數(shù)據(jù)庫來實(shí)現(xiàn) 分布式應(yīng)用的數(shù)據(jù)唯一性,即使使用預(yù)生成方案,也會因為事務(wù)鎖的問題,高并發(fā)場景容易出現(xiàn)單點(diǎn)瓶頸。
適用場景:單數(shù)據(jù)庫實(shí)例的表ID(包含主從同步場景),部分按天計數(shù)的流水號等;分庫分表場景、全系統(tǒng)唯一性ID場景不適用。
Redis生成ID
也屬于完全依賴數(shù)據(jù)源的方式,通過Redis的INCR/INCRBY自增原子操作命令,能保證生成的ID肯定是唯一有序的,本質(zhì)上實(shí)現(xiàn)方式與數(shù)據(jù)庫一致。
優(yōu)點(diǎn):整體吞吐量比數(shù)據(jù)庫要高。
缺點(diǎn):Redis實(shí)例或集群宕機(jī)后,找回最新的ID值有點(diǎn)困難。
適用場景:比較適合計數(shù)場景,如用戶訪問量,訂單流水號(日期+流水號)等。
UUID、GUID生成ID
UUID:按照OSF制定的標(biāo)準(zhǔn)計算,用到了以太網(wǎng)卡地址、納秒級時間、芯片ID碼和許多可能的數(shù)字。由以下幾部分的組合:當(dāng)前日期和時間(UUID的第一個部分與時間有關(guān),如果你在生成一個UUID之后,過幾秒又生成一個UUID,則第一個部分不同,其余相同),時鐘序列,全局唯一的IEEE機(jī)器識別號(如果有網(wǎng)卡,從網(wǎng)卡獲得,沒有網(wǎng)卡以其他方式獲得)
GUID:微軟對UUID這個標(biāo)準(zhǔn)的實(shí)現(xiàn)。UUID還有其它各種實(shí)現(xiàn),不止GUID一種,不一一列舉了。
這兩種屬于不依賴數(shù)據(jù)源方式,真正的全球唯一性ID
優(yōu)點(diǎn):不依賴任何數(shù)據(jù)源,自行計算,沒有網(wǎng)絡(luò)ID,速度超快,并且全球唯一。
缺點(diǎn):沒有順序性,并且比較長(128bit),作為數(shù)據(jù)庫主鍵、索引會導(dǎo)致索引效率下降,空間占用較多。
適用場景:只要對存儲空間沒有苛刻要求的都能夠適用,比如各種鏈路追蹤、日志存儲等。
4、snowflake算法(雪花算法)生成ID
屬于半依賴數(shù)據(jù)源方式,原理是使用Long類型(64位),按照一定的規(guī)則進(jìn)行填充:時間(毫秒級)+集群ID+機(jī)器ID+序列號,每部分占用的位數(shù)可以根據(jù)實(shí)際需要分配,其中集群ID和機(jī)器ID這兩部分,在實(shí)際應(yīng)用場景中要依賴外部參數(shù)配置或數(shù)據(jù)庫記錄。
優(yōu)點(diǎn):高性能、低延遲、去中心化、按時間有序
缺點(diǎn):要求機(jī)器時鐘同步(到秒級即可)
適用場景:分布式應(yīng)用環(huán)境的數(shù)據(jù)主鍵
雪花ID算法聽起來是不是特別適用分布式架構(gòu)場景?照目前來看是的,接下來我們重點(diǎn)講解它的原理和最佳實(shí)踐。
snowflake算法實(shí)現(xiàn)原理
snowflake算法來源于Twitter,使用scala語言實(shí)現(xiàn),利用Thrift框架實(shí)現(xiàn)RPC接口調(diào)用,最初的項目起因是數(shù)據(jù)庫從mysql遷移到Cassandra,Cassandra沒有現(xiàn)成可用 的ID生成機(jī)制,就催生了這個項目,現(xiàn)有的github源碼有興趣可以去看看。
snowflake算法的特性是有序、唯一,并且要求高性能,低延遲(每臺機(jī)器每秒至少生成10k條數(shù)據(jù),并且響應(yīng)時間在2ms以內(nèi)),要在分布式環(huán)境(多集群,跨機(jī)房)下使用,因此snowflake算法得到的ID是分段組成的:
與指定日期的時間差(毫秒級),41位,夠用69年
集群ID + 機(jī)器ID, 10位,最多支持1024臺機(jī)器
序列,12位,每臺機(jī)器每毫秒內(nèi)最多產(chǎn)生4096個序列號
如圖所示:
1bit:符號位,固定是0,表示全部ID都是正整數(shù)
41bit:毫秒數(shù)時間差,從指定的日期算起,夠用69年,我們知道用Long類型表示的時間戳是從1970-01-01 00:00:00開始算起的,咱們這里的時間戳可以指定日期,如2019-10-23 00:00:00
10bit:機(jī)器ID,有異地部署,多集群的也可以配置,需要線下規(guī)劃好各地機(jī)房,各集群,各實(shí)例ID的編號
12bit:序列ID,前面都相同的話,最多可以支持到4096個
以上的位數(shù)分配只是官方建議的,我們可以根據(jù)實(shí)際需要自行分配,比如說我們的應(yīng)用機(jī)器數(shù)量最多也就幾十臺,但并發(fā)數(shù)很大,我們就可以將10bit減少到8bit,序列部分從12bit增加到14bit等等
當(dāng)然每部分的含義也可以自由替換,如中間部分的機(jī)器ID,如果是云計算、容器化的部署環(huán)境,隨時有擴(kuò)容,縮減機(jī)器的操作,通過線下規(guī)劃去配置實(shí)例的ID不太現(xiàn)實(shí),就可以替換為實(shí)例每重啟一次,拿一次自增長的ID作為該部分的內(nèi)容,下文會講解。
github上也有大神用Java做了snowflake最基本的實(shí)現(xiàn),這里直接查看源碼:
snowflake java版源碼
/**
* twitter的snowflake算法 -- java實(shí)現(xiàn)
*
* @author beyond
* @date 2016/11/26
*/
public class SnowFlake {
/**
* 起始的時間戳
*/
private final static long START_STMP = 1480166465631L;
/**
* 每一部分占用的位數(shù)
*/
private final static long SEQUENCE_BIT = 12; //序列號占用的位數(shù)
private final static long MACHINE_BIT = 5; //機(jī)器標(biāo)識占用的位數(shù)
private final static long DATACENTER_BIT = 5;//數(shù)據(jù)中心占用的位數(shù)
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //數(shù)據(jù)中心
private long machineId; //機(jī)器標(biāo)識
private long sequence = 0L; //序列號
private long lastStmp = -1L;//上一次時間戳
public SnowFlake(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 產(chǎn)生下一個ID
*
* @return
*/
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒內(nèi),序列號自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列數(shù)已經(jīng)達(dá)到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒內(nèi),序列號置為0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //時間戳部分
| datacenterId << DATACENTER_LEFT //數(shù)據(jù)中心部分
| machineId << MACHINE_LEFT //機(jī)器標(biāo)識部分
| sequence; //序列號部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
SnowFlake snowFlake = new SnowFlake(2, 3);
for (int i = 0; i < (1 << 12); i++) {
System.out.println(snowFlake.nextId());
}
}
}
基本上通過位移操作,將每段含義的數(shù)值,移到相應(yīng)的位置上,如機(jī)器ID這里由數(shù)據(jù)中心+機(jī)器標(biāo)識組成,所以,機(jī)器標(biāo)識向左移12位,就是它的位置,數(shù)據(jù)中心的編號向左移17位,時間戳的值向左移22位,每部分占據(jù)自己的位置,各不干涉,由此組成一個完整的ID值。
這里就是snowflake最基礎(chǔ)的實(shí)現(xiàn)原理,如果有些java基礎(chǔ)知識不記得了建議查一下資料,如二進(jìn)制-1的表示是0xffff(里面全是1),<
了解snowflake的基本實(shí)現(xiàn)原理,可以通過提前規(guī)劃好機(jī)器標(biāo)識來實(shí)現(xiàn),但目前的分布式生產(chǎn)環(huán)境,借用了多種云計算、容器化技術(shù),實(shí)例的個數(shù)隨時有變化,還需要處理服務(wù)器實(shí)例時鐘回?fù)艿膯栴},固定規(guī)劃ID然后通過配置來使用snowflake的場景可行性不高,一般是自動啟停,增減機(jī)器,這樣就需要對snowflake進(jìn)行一些改造才能更好地應(yīng)用到生產(chǎn)環(huán)境中。
百度uid-generator項目
UidGenerator項目基于snowflake原理實(shí)現(xiàn),只是修改了機(jī)器ID部分的定義(實(shí)例重啟的次數(shù)),并且64位bit的分配支持配置,官方提供的默認(rèn)分配方式如下圖:
Snowflake算法描述:指定機(jī)器 & 同一時刻 & 某一并發(fā)序列,是唯一的。據(jù)此可生成一個64 bits的唯一ID(long)。
sign(1bit) 固定1bit符號標(biāo)識,即生成的UID為正數(shù)。
delta seconds (28 bits)
當(dāng)前時間,相對于時間基點(diǎn)"2016-05-20"的增量值,單位:秒,最多可支持約8.7年
worker id (22 bits) 機(jī)器id,最多可支持約420w次機(jī)器啟動。內(nèi)置實(shí)現(xiàn)為在啟動時由數(shù)據(jù)庫分配,默認(rèn)分配策略為用后即棄,后續(xù)可提供復(fù)用策略。
sequence (13 bits) 每秒下的并發(fā)序列,13 bits可支持每秒8192個并發(fā)。
具體的實(shí)現(xiàn)有兩種,一種是實(shí)時生成ID,另一種是預(yù)先生成ID方式
DefaultUidGenerator
啟動時向數(shù)據(jù)庫WORKER_NODE表插入當(dāng)前實(shí)例的IP,Port等信息,再獲取該數(shù)據(jù)的自增長ID作為機(jī)器ID部分。
簡易流程圖如下:
提供獲取ID的方法,并且檢測是否有時鐘回?fù)?#xff0c;有回?fù)墁F(xiàn)象直接拋出異常,當(dāng)前版本不支持時鐘順撥后漂移操作。簡易流程圖如下:
核心代碼如下:
/**
* Get UID
*
* @return UID
* @throws UidGenerateException in the case: Clock moved backwards; Exceeds the max timestamp
*/
protected synchronized long nextId() {
long currentSecond = getCurrentSecond();
// Clock moved backwards, refuse to generate uid
if (currentSecond < lastSecond) {
long refusedSeconds = lastSecond - currentSecond;
throw new UidGenerateException("Clock moved backwards. Refusing for %d seconds", refusedSeconds);
}
// At the same second, increase sequence
if (currentSecond == lastSecond) {
sequence = (sequence + 1) & bitsAllocator.getMaxSequence();
// Exceed the max sequence, we wait the next second to generate uid
if (sequence == 0) {
currentSecond = getNextSecond(lastSecond);
}
// At the different second, sequence restart from zero
} else {
sequence = 0L;
}
lastSecond = currentSecond;
// Allocate bits for UID
return bitsAllocator.allocate(currentSecond - epochSeconds, workerId, sequence);
}
CachedUidGenerator
機(jī)器ID的獲取方法與上一種相同,這種是預(yù)先生成一批ID,放在一個RingBuffer環(huán)形數(shù)組里,供客戶端使用,當(dāng)可用數(shù)據(jù)低于閥值時,再次調(diào)用批量生成方法,屬于用空間換時間的做法,可以提高整個ID的吞吐量。
與DefaultUidGenerator相比較,初始化時多了填充RingBuffer環(huán)形數(shù)組的邏輯,簡單流程圖如下:
核心代碼:
/**
* Initialize RingBuffer & RingBufferPaddingExecutor
*/
private void initRingBuffer() {
// initialize RingBuffer
int bufferSize = ((int) bitsAllocator.getMaxSequence() + 1) << boostPower;
this.ringBuffer = new RingBuffer(bufferSize, paddingFactor);
LOGGER.info("Initialized ring buffer size:{}, paddingFactor:{}", bufferSize, paddingFactor);
// initialize RingBufferPaddingExecutor
boolean usingSchedule = (scheduleInterval != null);
this.bufferPaddingExecutor = new BufferPaddingExecutor(ringBuffer, this::nextIdsForOneSecond, usingSchedule);
if (usingSchedule) {
bufferPaddingExecutor.setScheduleInterval(scheduleInterval);
}
LOGGER.info("Initialized BufferPaddingExecutor. Using schdule:{}, interval:{}", usingSchedule, scheduleInterval);
// set rejected put/take handle policy
this.ringBuffer.setBufferPaddingExecutor(bufferPaddingExecutor);
if (rejectedPutBufferHandler != null) {
this.ringBuffer.setRejectedPutHandler(rejectedPutBufferHandler);
}
if (rejectedTakeBufferHandler != null) {
this.ringBuffer.setRejectedTakeHandler(rejectedTakeBufferHandler);
}
// fill in all slots of the RingBuffer
bufferPaddingExecutor.paddingBuffer();
// start buffer padding threads
bufferPaddingExecutor.start();
}
public synchronized boolean put(long uid) {
long currentTail = tail.get();
long currentCursor = cursor.get();
// tail catches the cursor, means that you can't put any cause of RingBuffer is full
long distance = currentTail - (currentCursor == START_POINT ? 0 : currentCursor);
if (distance == bufferSize - 1) {
rejectedPutHandler.rejectPutBuffer(this, uid);
return false;
}
// 1. pre-check whether the flag is CAN_PUT_FLAG
int nextTailIndex = calSlotIndex(currentTail + 1);
if (flags[nextTailIndex].get() != CAN_PUT_FLAG) {
rejectedPutHandler.rejectPutBuffer(this, uid);
return false;
}
// 2. put UID in the next slot
// 3. update next slot' flag to CAN_TAKE_FLAG
// 4. publish tail with sequence increase by one
slots[nextTailIndex] = uid;
flags[nextTailIndex].set(CAN_TAKE_FLAG);
tail.incrementAndGet();
// The atomicity of operations above, guarantees by 'synchronized'. In another word,
// the take operation can't consume the UID we just put, until the tail is published(tail.incrementAndGet())
return true;
}
ID獲取邏輯,由于有RingBuffer這個緩沖數(shù)組存在,獲取ID直接從RingBuffer取出即可,同時RingBuffer自身校驗何時再觸發(fā)重新批量生成即可,這里獲取的ID值與DefaultUidGenerator的明顯區(qū)別是,DefaultUidGenerator獲取的ID,時間戳部分就是當(dāng)前時間的,CachedUidGenerator里獲取的是填充時的時間戳,并不是獲取時的時間,不過關(guān)系不大,都是不重復(fù)的,一樣用。簡易流程圖如下:
核心代碼:
public long take() {
// spin get next available cursor
long currentCursor = cursor.get();
long nextCursor = cursor.updateAndGet(old -> old == tail.get() ? old : old + 1);
// check for safety consideration, it never occurs
Assert.isTrue(nextCursor >= currentCursor, "Curosr can't move back");
// trigger padding in an async-mode if reach the threshold
long currentTail = tail.get();
if (currentTail - nextCursor < paddingThreshold) {
LOGGER.info("Reach the padding threshold:{}. tail:{}, cursor:{}, rest:{}", paddingThreshold, currentTail,
nextCursor, currentTail - nextCursor);
bufferPaddingExecutor.asyncPadding();
}
// cursor catch the tail, means that there is no more available UID to take
if (nextCursor == currentCursor) {
rejectedTakeHandler.rejectTakeBuffer(this);
}
// 1. check next slot flag is CAN_TAKE_FLAG
int nextCursorIndex = calSlotIndex(nextCursor);
Assert.isTrue(flags[nextCursorIndex].get() == CAN_TAKE_FLAG, "Curosr not in can take status");
// 2. get UID from next slot
// 3. set next slot flag as CAN_PUT_FLAG.
long uid = slots[nextCursorIndex];
flags[nextCursorIndex].set(CAN_PUT_FLAG);
// Note that: Step 2,3 can not swap. If we set flag before get value of slot, the producer may overwrite the
// slot with a new UID, and this may cause the consumer take the UID twice after walk a round the ring
return uid;
}
另外有個細(xì)節(jié)可以了解一下,RingBuffer的數(shù)據(jù)都是使用數(shù)組來存儲的,考慮CPU Cache的結(jié)構(gòu),tail和cursor變量如果直接用原生的AtomicLong類型,tail和cursor可能會緩存在同一個cacheLine中,多個線程讀取該變量可能會引發(fā)CacheLine的RFO請求,反而影響性能,為了防止偽共享問題,特意填充了6個long類型的成員變量,加上long類型的value成員變量,剛好占滿一個Cache Line(Java對象還有8byte的對象頭),這個叫CacheLine補(bǔ)齊,有興趣可以了解一下,源碼如下:
public class PaddedAtomicLong extends AtomicLong {
private static final long serialVersionUID = -3415778863941386253L;
/** Padded 6 long (48 bytes) */
public volatile long p1, p2, p3, p4, p5, p6 = 7L;
/**
* Constructors from {@link AtomicLong}
*/
public PaddedAtomicLong() {
super();
}
public PaddedAtomicLong(long initialValue) {
super(initialValue);
}
/**
* To prevent GC optimizations for cleaning unused padded references
*/
public long sumPaddingToPreventOptimization() {
return p1 + p2 + p3 + p4 + p5 + p6;
}
}
以上是百度uid-generator項目的主要描述,我們可以發(fā)現(xiàn),snowflake算法在落地時有一些變化,主要體現(xiàn)在機(jī)器ID的獲取上,尤其是分布式集群環(huán)境下面,實(shí)例自動伸縮,docker容器化的一些技術(shù),使得靜態(tài)配置項目ID,實(shí)例ID可行性不高,所以這些轉(zhuǎn)換為按啟動次數(shù)來標(biāo)識。
美團(tuán)ecp-uid項目
在uidGenerator方面,美團(tuán)的項目源碼直接集成百度的源碼,略微將一些Lambda表達(dá)式換成原生的java語法,例如:
// com.myzmds.ecp.core.uid.baidu.impl.CachedUidGenerator類的initRingBuffer()方法
// 百度源碼
this.bufferPaddingExecutor = new BufferPaddingExecutor(ringBuffer, this::nextIdsForOneSecond, usingSchedule);
// 美團(tuán)源碼
this.bufferPaddingExecutor = new BufferPaddingExecutor(ringBuffer, new BufferedUidProvider() {
@Override
public List provide(long momentInSecond) {
return nextIdsForOneSecond(momentInSecond);
}
}, usingSchedule);
并且在機(jī)器ID生成方面,引入了Zookeeper,Redis這些組件,豐富了機(jī)器ID的生成和獲取方式,實(shí)例編號可以存儲起來反復(fù)使用,不再是數(shù)據(jù)庫單調(diào)增長這一種了。
結(jié)束語
本篇簡單介紹了snowflake算法的原理及落地過程中的改造,在此學(xué)習(xí)了優(yōu)秀的開源代碼,并挑出部分進(jìn)行了簡單的示例,美團(tuán)的ecp-uid項目不但集成了百度現(xiàn)有的UidGenerator算法,原生的snowflake算法,還包含優(yōu)秀的leaf segment算法,鑒于篇幅沒有詳盡描述。文章內(nèi)有任何不正確或不詳盡之處請留言指出,謝謝。
總結(jié)
以上是生活随笔為你收集整理的mysql snowflake_一篇文章彻底搞懂snowflake算法及百度美团的最佳实践的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql5.7 skip ssl_My
- 下一篇: mysql异机还原_利用RMAN进行异机