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

时间:2017-11-14 11:35:33

标签: python algorithm

我有以下类创建一些comment并将其保存到必须包含唯一注释ID的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)

这是好的实施吗?如何改进?

2 个答案:

答案 0 :(得分:0)

我认为这不是一个好方法。您可以为每个评论生成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)

答案 1 :(得分:0)

如果您没有RsuService类的并发操作案例,我认为这是一个很好的实现。

但是如果同时创建RsuService的两个或更多对象,它可能会失败。在python中,Beacuse +=操作是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()