如何保证 DynamoDB 中的业务规则?
How to guarantee a business rule in DynamoDB?
我们有一个业务规则,一个帐户在任何给定时间只能有 3 个项目。
为了保持高效,我们在“userData”字段中跟踪项目数量,而不是执行 COUNT 查询
考虑 DynamoDB 中已有的以下示例对象:
userData : { createdProjects : 2 }
project1 : { id : 1 }
project2 : { id : 2 }
为了强制执行此规则,我们在创建项目时做了以下操作(伪代码)
in transaction:
putItem(key = "project3", object = { id : 3 })
updateItem(
key = "userData",
expression = "createdProjects = createdProjects + 1"
condition = "createdProjects < 3"
)
现在,如果用户试图同时用两台电脑创建一个项目,比方说,DynamoDB 会保证他不能创建超过 3 个吗?
我知道有类似的问题this one,但我想知道这是否也适用于交易,因为我的条件是在另一个对象中。
另外,我的伪代码是最好的方法吗?对其他方式开放
您可以为此使用交易。
只需将 PutItem
请求和 UpdateItem
请求包含在交易中的条件中,两者都将完成或其中 none 个。
事务是提供这种全有或全无行为的方式。
With the transaction write API, you can group multiple Put
, Update
, Delete
, and ConditionCheck
actions. You can then submit the actions as a single TransactWriteItems
operation that either succeeds or fails as a unit. The same is true for multiple Get actions, which you can group and submit as a single TransactGetItems
operation.
— docs
我们有一个业务规则,一个帐户在任何给定时间只能有 3 个项目。
为了保持高效,我们在“userData”字段中跟踪项目数量,而不是执行 COUNT 查询
考虑 DynamoDB 中已有的以下示例对象:
userData : { createdProjects : 2 }
project1 : { id : 1 }
project2 : { id : 2 }
为了强制执行此规则,我们在创建项目时做了以下操作(伪代码)
in transaction:
putItem(key = "project3", object = { id : 3 })
updateItem(
key = "userData",
expression = "createdProjects = createdProjects + 1"
condition = "createdProjects < 3"
)
现在,如果用户试图同时用两台电脑创建一个项目,比方说,DynamoDB 会保证他不能创建超过 3 个吗?
我知道有类似的问题this one,但我想知道这是否也适用于交易,因为我的条件是在另一个对象中。
另外,我的伪代码是最好的方法吗?对其他方式开放
您可以为此使用交易。
只需将 PutItem
请求和 UpdateItem
请求包含在交易中的条件中,两者都将完成或其中 none 个。
事务是提供这种全有或全无行为的方式。
With the transaction write API, you can group multiple
Put
,Update
,Delete
, andConditionCheck
actions. You can then submit the actions as a singleTransactWriteItems
operation that either succeeds or fails as a unit. The same is true for multiple Get actions, which you can group and submit as a singleTransactGetItems
operation.— docs