用Python写一个雪花算法
时间: 2024-04-12 20:07:59 浏览: 23
雪花算法是一种生成唯一ID的算法,其特点是不依赖于任何数据库或第三方服务,可以在分布式系统中保证ID的唯一性。下面是一个用Python实现雪花算法的示例代码:
```python
import time
class SnowflakeIDGenerator:
def __init__(self, datacenter_id, worker_id):
self.twepoch = 1288834974657
self.datacenter_id = datacenter_id
self.worker_id = worker_id
self.sequence = 0
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_bits = 12
self.worker_id_shift = self.sequence_bits
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 generate_id(self):
timestamp = self.time_gen()
if timestamp < self.last_timestamp:
raise Exception("Clock moved backwards, refusing to generate id")
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 time_gen(self):
return int(time.time() * 1000)
def til_next_millis(self, last_timestamp):
timestamp = self.time_gen()
while timestamp <= last_timestamp:
timestamp = self.time_gen()
return timestamp
```
使用示例:
```python
id_gen = SnowflakeIDGenerator(datacenter_id=1, worker_id=1)
print(id_gen.generate_id())
```
这个示例生成的ID是一个64位的整数,其中前41位是时间戳,接着的5位是数据中心ID,5位是工作机器ID,最后的12位是序列号。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)