这是一种现象,即使用 lambda 使用 put_item 请求并发写入 dynamodb 表,写入会失败而不会引发任何异常。
我有一个 dynamodb 表设置来使用按需读写。 一次最多有 100 个 lamdbda 写入该表。 我已经包含了发生这种情况时 cloudwatch 的输出。
import boto3
from botocore.exceptions import ClientError
import time
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('myTable')
def lambda_handler(event, context, items, retries=5):
for item in items:
for i in range(retries):
try:
table.put_item(Item=item)
# Apply a check to verify that the item is loaded
response = table.get_item(Key={'PrimaryKey': item['PrimaryKey']})
loaded_item = response.get('Item')
if loaded_item == item:
break
else:
raise ValueError("Item verification failed")
except ClientError as e:
if e.response['Error']['Code'] in ['ProvisionedThroughputExceededException', 'ThrottlingException']:
time.sleep(2 ** i) # Exponential backoff
else:
raise
else:
print(f"Failed to write item after retries: {item}")
# Example usage
items = [
{'PrimaryKey': 'value1', 'Attribute': 'value1'},
{'PrimaryKey': 'value2', 'Attribute': 'value2'},
# Add more items as needed
]
lambda_handler(None, None, items)
您遇到此问题是因为您的读数最终是一致的。
这样做:
table.get_item(Key={'PrimaryKey': item['PrimaryKey'],
ConsistentRead=True}