按時(shí)間分表id如何生成器

1. 時(shí)間戳:使用當(dāng)前的時(shí)間戳作為ID的一部分。2. 機(jī)器標(biāo)識:確保ID在多臺機(jī)器上唯一。```pythonimport timeimport threadingcla...
1. 時(shí)間戳:使用當(dāng)前的時(shí)間戳作為ID的一部分。
2. 機(jī)器標(biāo)識:確保ID在多臺機(jī)器上唯一。
```python
import time
import threading
class IDGenerator:
def __init__(self, machine_id):
self.machine_id = machine_id
self.lock = threading.Lock()
self.sequence = 0
def _get_timestamp(self):
return int(time.time() 1000) 獲取當(dāng)前時(shí)間戳,單位毫秒
def _get_sequence(self):
with self.lock:
if self.sequence == 0:
time.sleep(0.001) 短暫休眠,等待下一秒
return self.sequence
def generate_id(self):
timestamp = self._get_timestamp()
machine_id = self.machine_id
sequence = self._get_sequence()
return f"{timestamp:016d
本文鏈接:http:///bian/346352.html