雪花算法python实现
import time
class Snowflake(object):
def __init__(self, worker_id=0, datacenter_id=0):
self.worker_id = worker_id & 0xffff
self.datacenter_id = datacenter_id & 0xff
# 设置起始时间为2019年1月1日零点
self.twepoch = int(time.mktime((2019, 1, 1, 0, 0, 0, 0, 0, -1))) * 1000
def generate_snowflake(self):
timestamp = int(round(time.time() * 1000))
if timestamp < self.twepoch:
raise Exception("Invalid system clock")
sequence = 0
while True:
current_timestamp = (timestamp - self.twepoch) // 41
last_timestamp = current_timestamp % 8191 + 1
if last_timestamp == 8192 and sequence == 7:
timestamp += 1
else:
break
snowflake = ((current_timestamp << 32) | (last_timestamp << 16) | (sequence << 12) | (self.worker_id << 5) | self.datacenter_id)
return str(hex(snowflake)).replace('L', '')[2:]
# 创建Snowflake对象并指定工作节点ID和数据中心ID(根据需要自行调整)
sf = Snowflake(worker_id=1, datacenter_id=1)
# 生成雪花算法生成的十六进制字符串
result = sf.generate_snowflake()
print(result)
603

被折叠的 条评论
为什么被折叠?



