Dynamo DB上带Python UUID的AWS Lambda(概念)
这是一个概念问题: 我们希望在AWS Lambda上运行代码时,为Dynamo DB表创建一个唯一的主键 如果我们在AWS Lambda上使用python内置函数uuid为dynamo DB数据库创建一个唯一的键,那么它是否有可能创建一个双倍的键,例如,如果我们的dynamo DB数据库中有50-200亿个项 例如,我知道在普通应用程序中,使用双uuid密钥的可能性非常低,几乎是不可能的 据我所知,每次uuid运行时,它都会确保不会通过在内存中保存一些以前的值来创建double 但是,我不确定Lambda是否只是在同一个python控制台上反复运行下面的函数(并保存uuid以确保其唯一性),或者是否正在创建多个单独的控制台实例并分别运行它们(而不是保存uuid的内存) 虽然这是一个概念问题,但这里有一些示例代码:Dynamo DB上带Python UUID的AWS Lambda(概念),python,amazon-web-services,amazon-dynamodb,aws-lambda,Python,Amazon Web Services,Amazon Dynamodb,Aws Lambda,这是一个概念问题: 我们希望在AWS Lambda上运行代码时,为Dynamo DB表创建一个唯一的主键 如果我们在AWS Lambda上使用python内置函数uuid为dynamo DB数据库创建一个唯一的键,那么它是否有可能创建一个双倍的键,例如,如果我们的dynamo DB数据库中有50-200亿个项 例如,我知道在普通应用程序中,使用双uuid密钥的可能性非常低,几乎是不可能的 据我所知,每次uuid运行时,它都会确保不会通过在内存中保存一些以前的值来创建double 但是,我不确定L
from __future__ import print_function
from decimal import *
import boto3
import json
from locale import str
import uuid
def my_handler(event, context):
description = event['description']
spot_id = uuid.uuid4() #Unique identifier for spot
dynamodb = boto3.client('dynamodb')
tablesinfo = "sinfo"
dynamodb.put_item(
TableName = tablesinfo, Item = {
'spot_id':{'S' : str(spot_id)},
'description': {'S' : description}
}
)
return {'spot_id' : spot_id}
AmazonAWS有自己的示例,用于在Lambda中使用Python创建UUID并将其存储在elasticache中。Amazon没有明确表示每次都会创建一个唯一的条目,但是您可以将此与检查结合起来,查看生成的UUID在插入之前是否已经在DynamoDB中。检查UUID是否已经存在的缺点是,这将使用DynamoDB表上的一些读取容量,因此从概念上讲,这是您的成本 这是来自AWS的代码,如果您通过检查表中是否已经创建了UUID来调整它以适合DynamoDB,那么这将起作用: 发件人:
您的代码示例不包括生成uuid的部分。@Oin我更新了代码,我意识到这可能会让人困惑,但这主要是一个基于概念的问题。您对这个问题有什么回答吗?我又得到了同样的UUID&again@Himanshu不,我没有,但我假设如果您一次又一次地获得相同的UUID,那么每次运行代码时它都必须运行新的独立实例,而不是将其保存在内存中
from __future__ import print_function
import time
import uuid
import sys
import socket
import elasticache_auto_discovery
from pymemcache.client.hash import HashClient
#elasticache settings
elasticache_config_endpoint = "your-elasticache-cluster-endpoint:port"
nodes = elasticache_auto_discovery.discover(elasticache_config_endpoint)
nodes = map(lambda x: (x[1], int(x[2])), nodes)
memcache_client = HashClient(nodes)
def handler(event, context):
"""
This function puts into memcache and get from it.
Memcache is hosted using elasticache
"""
#Create a random UUID... this will the sample element we add to the cache.
uuid_inserted = uuid.uuid4().hex
#Put the UUID to the cache.
memcache_client.set('uuid', uuid_inserted)
#Get item (UUID) from the cache.
uuid_obtained = memcache_client.get('uuid')
if uuid_obtained == uuid_inserted:
# this print should go to the CloudWatch Logs and Lambda console.
print ("Success: Fetched value %s from memcache" %(uuid_inserted))
else:
raise Exception("Value is not the same as we put :(. Expected %s got %s" %(uuid_inserted, uuid_obtained))
return "Fetched value from memcache: " + uuid_obtained