您好,登錄后才能下訂單哦!
這篇文章主要介紹了基于python實(shí)現(xiàn)雪花算法過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
Snowflake是Twitter提出來的一個(gè)算法,其目的是生成一個(gè)64bit的整數(shù):
上面只是一個(gè)將64bit劃分的標(biāo)準(zhǔn),當(dāng)然也不一定這么做,可以根據(jù)不同業(yè)務(wù)的具體場景來劃分,比如下面給出一個(gè)業(yè)務(wù)場景:
機(jī)器三地部署我們可以用3bit總共8來表示機(jī)房位置,當(dāng)前的機(jī)器10臺,為了保證擴(kuò)展到百臺那么可以用7bit 128來表示,時(shí)間位依然是41bit,那么還剩下64-10-3-7-41-1 = 2bit,還剩下2bit可以用來進(jìn)行擴(kuò)展。
時(shí)鐘回?fù)?br />
因?yàn)闄C(jī)器的原因會發(fā)生時(shí)間回?fù)埽覀兊难┗ㄋ惴ㄊ菑?qiáng)依賴我們的時(shí)間的,如果時(shí)間發(fā)生回?fù)埽锌赡軙芍貜?fù)的ID,在我們上面的nextId中我們用當(dāng)前時(shí)間和上一次的時(shí)間進(jìn)行判斷,如果當(dāng)前時(shí)間小于上一次的時(shí)間那么肯定是發(fā)生了回?fù)埽惴〞苯訏伋霎惓?
# Twitter's Snowflake algorithm implementation which is used to generate distributed IDs. # https://github.com/twitter-archive/snowflake/blob/snowflake-2010/src/main/scala/com/twitter/service/snowflake/IdWorker.scala import time import logging from .exceptions import InvalidSystemClock # 64位ID的劃分 WORKER_ID_BITS = 5 DATACENTER_ID_BITS = 5 SEQUENCE_BITS = 12 # 最大取值計(jì)算 MAX_WORKER_ID = -1 ^ (-1 << WORKER_ID_BITS) # 2**5-1 0b11111 MAX_DATACENTER_ID = -1 ^ (-1 << DATACENTER_ID_BITS) # 移位偏移計(jì)算 WOKER_ID_SHIFT = SEQUENCE_BITS DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS # 序號循環(huán)掩碼 SEQUENCE_MASK = -1 ^ (-1 << SEQUENCE_BITS) # Twitter元年時(shí)間戳 TWEPOCH = 1288834974657 logger = logging.getLogger('flask.app') class IdWorker(object): """ 用于生成IDs """ def __init__(self, datacenter_id, worker_id, sequence=0): """ 初始化 :param datacenter_id: 數(shù)據(jù)中心(機(jī)器區(qū)域)ID :param worker_id: 機(jī)器ID :param sequence: 其實(shí)序號 """ # sanity check if worker_id > MAX_WORKER_ID or worker_id < 0: raise ValueError('worker_id值越界') if datacenter_id > MAX_DATACENTER_ID or datacenter_id < 0: raise ValueError('datacenter_id值越界') self.worker_id = worker_id self.datacenter_id = datacenter_id self.sequence = sequence self.last_timestamp = -1 # 上次計(jì)算的時(shí)間戳 def _gen_timestamp(self): """ 生成整數(shù)時(shí)間戳 :return:int timestamp """ return int(time.time() * 1000) def get_id(self): """ 獲取新ID :return: """ timestamp = self._gen_timestamp() # 時(shí)鐘回?fù)? if timestamp < self.last_timestamp: logging.error('clock is moving backwards. Rejecting requests until {}'.format(self.last_timestamp)) raise InvalidSystemClock if timestamp == self.last_timestamp: self.sequence = (self.sequence + 1) & SEQUENCE_MASK if self.sequence == 0: timestamp = self._til_next_millis(self.last_timestamp) else: self.sequence = 0 self.last_timestamp = timestamp new_id = ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT) | (self.datacenter_id << DATACENTER_ID_SHIFT) | \ (self.worker_id << WOKER_ID_SHIFT) | self.sequence return new_id def _til_next_millis(self, last_timestamp): """ 等到下一毫秒 """ timestamp = self._gen_timestamp() while timestamp <= last_timestamp: timestamp = self._gen_timestamp() return timestamp if __name__ == '__main__': worker = IdWorker(1, 2, 0) print(worker.get_id())
同文件夾下建立exceptions.py
class InvalidSystemClock(Exception): """ 時(shí)鐘回?fù)墚惓? """ pass
配置文件中添加,對應(yīng)的是機(jī)器ID和序列號
# Snowflake ID Worker 參數(shù) DATACENTER_ID = 0 WORKER_ID = 0 SEQUENCE = 0
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。