AWS DynamoDB 如何防止事务重复记录?
How does AWS DynamoDB prevent from duplicated records by transaction?
我正在 AWS 中构建微服务,并计划将 DynamoDB 作为我的存储。由于微服务将被成千上万的客户端访问,并且多个 tables(例如 ECOMM_ORDERS 和 INVENTORY)将在 DynamoDB 中更新。在每个订单中,ECOMM_ORDERS 将插入一条订单记录,相关产品的库存将在 INVENTORY table.
中更新
我引用了 the official example,但它们不像传统的 SQL 事务那样工作(例如开始事务、回滚、提交)。在我的案例中,如何使用 DynamoDB 事务来防止重复记录? (通过错误处理?我应该如何回滚?我应该如何提交?)
DynamoDB 事务是一个 all-or-nothing 操作。 reads/writes 会一起成功或一起失败,所以不存在事务中一些操作失败而其他操作成功的可能性。单次写失败会导致事务中的所有写操作回滚。
您可以在交易中包含 ConditionExpressions in your PutItem
operations to confirm attribute_not_exists(primary_key)
on any of your items. You can also use a ConditionCheck 以确认交易期间的条件。
这个 blog post 给出了一些使用事务来模拟唯一约束的很好的例子。
此外,来自 this AWS blog post:
Items are not locked during a transaction. DynamoDB transactions
provide serializable isolation. If an item is modified outside of a
transaction while the transaction is in progress, the transaction is
canceled and an exception is thrown with details about which item or
items caused the exception.
我正在 AWS 中构建微服务,并计划将 DynamoDB 作为我的存储。由于微服务将被成千上万的客户端访问,并且多个 tables(例如 ECOMM_ORDERS 和 INVENTORY)将在 DynamoDB 中更新。在每个订单中,ECOMM_ORDERS 将插入一条订单记录,相关产品的库存将在 INVENTORY table.
中更新我引用了 the official example,但它们不像传统的 SQL 事务那样工作(例如开始事务、回滚、提交)。在我的案例中,如何使用 DynamoDB 事务来防止重复记录? (通过错误处理?我应该如何回滚?我应该如何提交?)
DynamoDB 事务是一个 all-or-nothing 操作。 reads/writes 会一起成功或一起失败,所以不存在事务中一些操作失败而其他操作成功的可能性。单次写失败会导致事务中的所有写操作回滚。
您可以在交易中包含 ConditionExpressions in your PutItem
operations to confirm attribute_not_exists(primary_key)
on any of your items. You can also use a ConditionCheck 以确认交易期间的条件。
这个 blog post 给出了一些使用事务来模拟唯一约束的很好的例子。
此外,来自 this AWS blog post:
Items are not locked during a transaction. DynamoDB transactions provide serializable isolation. If an item is modified outside of a transaction while the transaction is in progress, the transaction is canceled and an exception is thrown with details about which item or items caused the exception.