问题
I am working on an application written in Flask and backed by Amazon's DynamoDB accessed through boto.
For a specific use case, we need to retrieve a value from a table and then make it unavailable for other users.
However, by retrieving and then deleting the value, a race-condition could occur in between the retrieval and deletion.
Is there any way to retrieve an item from a table and immediately delete or update it in an atomic fashion?
回答1:
If your logic:
- get item
- delete
without any additional logic to determine whether deletion should occur, then you can actually send delete request immediately, here is example (I haven't checked it, mostly take from: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LowLevelJavaItemCRUD.html)
HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>();
key.put("Id", new AttributeValue().withN("101"));
DeleteItemRequest deleteItemRequest = new DeleteItemRequest()
.withTableName(tableName)
.withKey(key)
.withReturnValues(ReturnValue.ALL_OLD);
DeleteItemResult deleteItemResult = client.deleteItem(deleteItemRequest);
Map<String,AttributeValue> deletedItem = deleteItemResult.getAttributes();
Documentation:
withReturnValues
getAttributes
来源:https://stackoverflow.com/questions/22754415/dynamodb-how-to-retrieve-and-delete-pop-an-item