根据雪花算法生成平时订单的id的代码
时间: 2024-02-27 22:28:03 浏览: 97
利用雪花算法生成uuid
由于具体业务场景不清楚,下面提供一个示例代码,可根据实际情况进行修改和调整:
```
import random
import time
class SnowflakeIdGenerator:
def __init__(self, datacenter_id, machine_id):
self.datacenter_id = datacenter_id
self.machine_id = machine_id
self.sequence = 0
self.last_timestamp = -1
def generate_id(self):
timestamp = int(time.time() * 1000)
if timestamp < self.last_timestamp:
raise Exception("Clock moved backwards. Refusing to generate id.")
if timestamp == self.last_timestamp:
self.sequence = (self.sequence + 1) & 4095
if self.sequence == 0:
timestamp = self.wait_for_next_millis(timestamp)
else:
self.sequence = random.randint(0, 4095)
self.last_timestamp = timestamp
return (timestamp << 22) | (self.datacenter_id << 17) | (self.machine_id << 12) | self.sequence
def wait_for_next_millis(self, timestamp):
while timestamp <= self.last_timestamp:
timestamp = int(time.time() * 1000)
return timestamp
# 示例代码
id_generator = SnowflakeIdGenerator(1, 1)
for i in range(10):
print(id_generator.generate_id())
```
上述代码使用了雪花算法生成id,其中包含了数据中心id和机器id等信息,可根据实际情况进行配置和调整。在示例代码中,每生成一个id后,都会打印出来,可以根据实际需求将其存储到数据库中等。
阅读全文