使用DynamoDB乐观锁定的正确方法 [英] Correct way to use DynamoDB Optimistic Locking
问题描述
我正在尝试了解DynamoDB乐观锁定是否适合我的用例,还是应该做其他事情。
I'm trying to understand if DynamoDB Optimistic Locking is the correct thing for my use case or should I be doing something else.
我正在尝试做
function updateItem(String key) {
Item item = mapper.load(Item.class, key);
if (some condition) {
item.setValue(item.getValue() + 1);
mapper.save(item);
}
}
我想根据某些条件更新同一项目成功。我创建了一个version属性,以便乐观锁定起作用,当有多个请求进入时,只有一个请求会获取并更新数据。
I want to update the same item based on some condition succeeding. I've created a version attribute, so that Optimistic locking works and when I have multiple requests coming in, only one request gets and updates the data.
我正在尝试了解以下内容:
I'm trying to understand the following:
-
当其他某个线程尝试更新值但版本ID更改时会发生什么,我无法找不到引发异常的任何文档?
What happens when some other thread tries to update the value but the version id has changed, I couldn't find any documentation on what exception will be thrown?
我应该为此使用同步功能吗?考虑到会有多个请求?但是,在我看来,这似乎违反了乐观锁定的目的,因为我不在乎哪个请求首先获得访问权限。
Should I be using a synchronized function for this? Considering multiple requests will be coming in? But, to me this seems like it defeats the purpose of optimistic locking, since I don't care which request gets access first.
是否有替代解决方案
我已经阅读了以下文档:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking .html
I've been through the following documentation: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html
推荐答案
- 在其他情况下会发生什么线程尝试更新值,但是
版本ID更改了,我找不到任何有关抛出
异常的文档?
如果版本ID已更改,则似乎抛出ConditionalCheckFailedException。
It appears to throw a ConditionalCheckFailedException if the version ID has changed.
- 我应该使用同步功能吗?为此吗?考虑到
会有多个请求?但是,在我看来,
违反了乐观锁定的目的,因为我不在乎哪个
请求首先获得访问权限。
您是正确的,使用同步函数将无法达到乐观锁定的目的。两者都不需要。而且乐观锁定在分布式环境中起作用,在这种环境中更新可能不是由同一台服务器生成的。
You are correct, using a synchronized function would defeat the purpose of optimistic locking. You don't need both. And optimistic locking works in a distributed environment where updates may not be generated by the same servers.
- 是否有解决此问题的替代方法?
您可以使用低级DynamoDB API和条件更新。我认为这就是下方的乐观锁。如果您使用的语言不是Java或.Net,则必须使用低级API。由于您正在使用Java并且已经在使用高级API,因此我会坚持使用。
You could use the low-level DynamoDB API and Conditional Updates. I think that's what the Optimistic Locking is using underneath. If you were using a language other than Java or .Net you would have to use the low-level API. Since you are using Java and already working with the high-level API I would stick with that.
这篇关于使用DynamoDB乐观锁定的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!