使用专用序列表。如果您只有一个序列(例如 PostId),那么表中将只有一行具有两个属性。
是的,管理另一个表需要额外的成本和精力,但这是迄今为止我所知道的最好的解决方案,还没有看到其他人提到它。
该表应该有一个 key 属性作为主分区键,以及一个初始值为 1 的数字 value 属性(或任何您想要的初始值)。
每次您想要获取下一个可用密钥时,您都告诉 DynamoDB 这样做:
- 将
value 其中key = PostId 递增1,并在递增之前返回值。
请注意,这是一个单一的原子操作。 DynamoDB 处理自动递增,因此不存在并发问题。
在代码中,实现这一点的方法不止一种。这是一个例子:
Map<String,AttributeValue> key = new HashMap<>();
key.put("key", new AttributeValue("PostId"));
Map<String, AttributeValueUpdate> item = new HashMap<String, AttributeValueUpdate>();
item.put("value",
new AttributeValueUpdate()
.withAction(AttributeAction.ADD)
.withValue(1));
UpdateItemRequest request = new UpdateItemRequest("Sequences", key, item).withReturnValues(ReturnValue.ALL_OLD);
UpdateItemResult result = dynamoDBClient.updateItem(request);
Integer postId = Integer.parseInt(result.getAttributes().get("value").getN()); // <- this is the sequential ID you want to set to your post