如何使用计数技术生成唯一的int-id?

2024-09-28 17:06:01 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的类创建了一些comment并将其保存到dynamo db,dynamo db必须包含唯一的注释id。我不想重复rsu_id值。你知道吗

class RsuService(object):
    next_id = 0

    def __init__(self):
        self.rsu_id = RsuService.next_id
        RsuService.next_id += 1

    async def create(self, alert_id, text):
        message = {
            'event_id': alert_id,
            'text': text,
            'is_rsu': True,
            'comment_id': self.rsu_id
        }
        await save(message)

实施得好吗?如何改进?你知道吗


Tags: textselfidmessagedbasyncobjectinit
2条回答

我认为这是一个很好的实现,如果您没有使用RsuService类进行并发操作的情况。你知道吗

但如果同时创建RsuService的两个或多个对象,它可能会失败。因为+=操作在python中是not atomic。你知道吗

如果你有并发操作的情况,我建议你这样做。你知道吗

import threading
class RsuService(object):
    next_id = 0
    lock = threading.Lock() #lock shared by all objects of this class

def __init__(self):
    lock.acquire()
    self.rsu_id = RsuService.next_id
    RsuService.next_id += 1
    lock.release()

如果没有并发任务的情况,最好使用时间戳作为唯一id,因为如果重新启动程序,计数器将从头开始,这将是一个问题。你知道吗

import time
...
RsuService.next_id = time.time()

我认为这不是一个好办法。您可以为每个注释生成UUID并将其用作唯一id

import uuid

class RsuService(object):
    async def create(self, alert_id, text):
        message = {
            'event_id': alert_id,
            'text': text,
            'is_rsu': True,
            'comment_id': uuid.uuid4().hex
        }
        await save(message)

相关问题 更多 >