帮我写个雪花算法生成ID
时间: 2023-03-12 14:37:51 浏览: 141
多语言雪花算法里最好用的主键ID生成工具.zip
好的,下面是一个使用雪花算法生成ID的代码:
```
# coding: utf-8
import time
class SnowflakeIdGenerator:
def __init__(self, worker_id, datacenter_id):
self.worker_id = worker_id
self.datacenter_id = datacenter_id
self.twepoch = 1288834974657
self.worker_id_bits = 5
self.datacenter_id_bits = 5
self.max_worker_id = -1 ^ (-1 << self.worker_id_bits)
self.max_datacenter_id = -1 ^ (-1 << self.datacenter_id_bits)
self.sequence = 0
self.worker_id_shift = self.sequence_bits = 12
self.datacenter_id_shift = self.sequence_bits + self.worker_id_bits
self.timestamp_left_shift = self.sequence_bits + self.worker_id_bits + self.datacenter_id_bits
self.sequence_mask = -1 ^ (-1 << self.sequence_bits)
self.last_timestamp = -1
def get_timestamp(self):
return int(time.time() * 1000)
def generate_id(self):
timestamp = self.get_timestamp()
if timestamp < self.last_timestamp:
raise Exception("Clock moved backwards. Refusing to generate id for %d milliseconds" % (self.last_timestamp - timestamp))
if timestamp == self.last_timestamp:
self.sequence = (self.sequence + 1) & self.sequence_mask
if self.sequence == 0:
timestamp = self.til_next_millis(self.last_timestamp)
else:
self.sequence = 0
self.last_timestamp = timestamp
return ((timestamp - self.twepoch) << self.timestamp_left_shift) | (self.datacenter_id << self.datacenter_id_shift) | (self.worker_id << self.worker_id_shift) | self.sequence
def til_next_millis(self, last_timestamp):
timestamp = self.get_timestamp()
while timestamp <= last_timestamp:
timestamp = self.get_timestamp()
return timestamp
# 生成器实例
id_generator = SnowflakeIdGenerator(worker_id=1, datacenter_id=1)
# 生成ID
id = id_generator.generate_id()
print(id)
```
这段代码实现了雪花算法,可以生成全局唯一的ID。在这段代码中,worker_id和datacenter_id是可以自定义的,分别代表工作
阅读全文