基於雪花演算法生成64位ID

2021-10-09 12:33:27 字數 2503 閱讀 6849

import logging

import time

class

generator

(object):

""" 64位id 1(符號位不用) (41(毫秒)+4(機器id)+6(業務編碼)+12(重複累加))

基礎時間(毫秒): 1577808000000 2020/01/01/ 00:00

最大支援時間差: 2199023255551(0x1ffffffffffbit) 基於毫秒算大約可用69年(2199023255551/1000/60/60/24/365.25)

dc: 4bit (自動取值範圍[0,16))

worker: 6bit (自動取值範圍[0,64))

desc: 同一時刻產生4095個id,原理上支援每秒409.5萬個id,由於執行效率問題,本程式經測試每秒約能產生70萬個id

"""epoch_timestamp =

1577808000000

max_sequence =

4095

# 12bit 最大值

def__init__

(self, dc, worker)

: self.dc = dc

self.worker = worker

self.node_id =

((dc &

0xf)

<<6)

|(worker &

0x3f

)# 10bit = 4bit + 6bit

self.last_timestamp = self.epoch_timestamp

self.sequence =

0 self.sequence_overload =

0 self.errors =

0 self.generated_ids =

0def

get_next_id

(self)

:""" id生產

"""curr_time =

int(time.time()*

1000

)if curr_time < self.last_timestamp:

# stop handling requests til we've caught back up

self.errors +=

1raise exception(

'clock went backwards! %d < %d'

%(curr_time, self.last_timestamp)

)if curr_time > self.last_timestamp:

self.sequence =

0 self.last_timestamp = curr_time

self.sequence +=

1if self.sequence > self.max_sequence:

# the sequence is overload, just wait to next sequence

logging.warning(

'the sequence has been overload'

) self.sequence_overload +=

1 time.sleep(

0.001

)return self.get_next_id(

) diff_time = curr_time - self.epoch_timestamp

generated_id =

((diff_time &

0x1ffffffffff

)<<22)

|(self.node_id <<12)

| self.sequence

self.generated_ids +=

1return generated_id

@property

defstats

(self)

:""" 狀態查詢

"""return

defpressure_test

(self)

:""" 壓力測試

"""start_time =

int(time.time()*

1000

) end_time =

1000

+ start_time

id_num =

0while self.last_timestamp <= end_time:

self.get_next_id(

) id_num +=

1print

(id_num)

if __name__ ==

'__main__'

: a = generator(0,

0)a.pressure_test(

)

ID 生成器 雪花演算法

我們的業務需求中通常有需要一些唯一的id,來記錄我們某個資料的標識 看圖理解 詳細的看 注釋 public class snowflakeidworker if datacenterid maxdatacenterid datacenterid 0 this.workerid workerid th...

訂單Id生成之雪花演算法

不跟你多bb,上張圖好說話 為什麼 是64位呢,因為返回值是long型別是64位,但是第一位是符號位不可用,所有只剩下63位 時間戳的長度,決定了該演算法使用的年限,時間戳記錄的不是當前時間戳,而是當前時間戳和和起始時間戳的差值,起始時間戳由程式設計師自己設定 41位 按如下公式計算可用時間約為 1...

雪花演算法生成唯一ID

author ws description 雪花演算法生成唯一id datetime 2020 6 26 10 07 public class snowflake 起始的時間戳 2020 05 27 00 00 00 private final static long start stamp 159...