事务

使用TransactWriteItems命令可以将100个写请求同时写到DynamoDB,这些请求可以写到不同表里(但要在相同帐号相同region),这些请求是原子性的,要么全部成功,要么全部失败。

前面的实验中我们有几个表 Forum, ThreadReply。当Reply表中有新记录插入时,我们需要增加Forum表中Message字段的大小,这些操作需要在一个事务中完成。DynamoDB的事务支持幂等(idempotency),即使将相同的事务提交多次,DynamoDB保证只执行一次

当提交一次事务时,需要指定一个ClientRequestToken(即Idempotency Token,用于保证幂等性)

执行以下命令:

aws dynamodb transact-write-items --client-request-token TRANSACTION1 --transact-items '[
    {
        "Put": {
            "TableName" : "Reply",
            "Item" : {
                "Id" : {"S": "Amazon DynamoDB#DynamoDB Thread 2"},
                "ReplyDateTime" : {"S": "2021-04-27T17:47:30Z"},
                "Message" : {"S": "DynamoDB Thread 2 Reply 3 text"},
                "PostedBy" : {"S": "User C"}
            }
        }
    },
    {
        "Update": {
            "TableName" : "Forum",
            "Key" : {"Name" : {"S": "Amazon DynamoDB"}},
            "UpdateExpression": "ADD Messages :inc",
            "ExpressionAttributeValues" : { ":inc": {"N" : "1"} }
        }
    }
]'

查看Forum的内容,可以看到Messages被加1:

Look at the Forum item and you’ll see that the Messages count was incremented by 1, from 4 to 5.

aws dynamodb get-item \
    --table-name Forum \
    --key '{"Name" : {"S": "Amazon DynamoDB"}}'
...
"Messages": {
    "N": "5"
}
...

如果你重复运行一遍这个提交事务的命令,会发现

If you run the same transaction command again, with the same client-request-token value, you can verify that the other invocations of the transaction are essentially ignored and the Messages attributed remains at 5.

Now we need to do another transaction to reverse the above operation and clean up the table:

aws dynamodb transact-write-items --client-request-token TRANSACTION2 --transact-items '[
    {
        "Delete": {
            "TableName" : "Reply",
            "Key" : {
                "Id" : {"S": "Amazon DynamoDB#DynamoDB Thread 2"},
                "ReplyDateTime" : {"S": "2021-04-27T17:47:30Z"}
            }
        }
    },
    {
        "Update": {
            "TableName" : "Forum",
            "Key" : {"Name" : {"S": "Amazon DynamoDB"}},
            "UpdateExpression": "ADD Messages :inc",
            "ExpressionAttributeValues" : { ":inc": {"N" : "-1"} }
        }
    }
]'