import boto3
dynamodb = boto3.client('dynamodb')
table_name = 'my-table'
def lambda_handler(event, context):
# 请求中获取到表的主键键值对
user_id = event['user_id']
timestamp = event['timestamp']
# 计算待更新的属性值
updates = {
':one': {'N': '1'},
':timestamp': {'N': str(timestamp)},
}
# 使用ConditionExpression和UpdateExpression确保原子性更新
response = dynamodb.update_item(
TableName=table_name,
Key={'user_id': {'S': user_id}},
UpdateExpression='SET counter = counter + :one, last_updated = :timestamp',
ConditionExpression='attribute_not_exists(last_updated) OR last_updated < :timestamp',
ExpressionAttributeValues=updates,
ReturnValues='ALL_NEW',
)
return response['Attributes']
以上代码是一个AWS Lambda函数示例。它使用DynamoDB的UpdateItem API对user_id进行计数,同时设置最后一次更新的时间戳。通过使用ConditionExpression,它确保只有一个请求可以成功更新给定用户ID的counter值和last_updated属性。
下一篇:AWS抛出CORS