雪花算法python实现

雪花算法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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值