启用存活时间 (TTL) - Amazon DynamoDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

启用存活时间 (TTL)

可以在亚马逊 DynamoDB 控制台 () 中启用 ttLAWS Command Line Interface,AWS CLI也可以将亚马逊 Dy namoDB API 参考与任何假定的软件开发工具包一起使用。AWS在所有分区中启用 TTL 大约需要一个小时。

  1. 登录 AWS Management Console,打开 DynamoDB 控制台:https://console.aws.amazon.com/dynamodb/

  2. 选择 Tables (表),然后选择您要修改的表。

  3. 在 “其他设置” 选项卡的 “生存时间 (TTL)” 部分,选择 “开启” 以启用 TTL。

  4. 在表上启用 TTL 时,DynamoDB 要求您标识此服务在确定项目是否符合过期条件时将查找的特定属性名称。如下所示的 TTL 属性名称区分大小写,并且必须与读取和写入操作中定义的属性相匹配。不匹配将导致过期的项目被取消删除。重命名 TTL 属性需要您禁用 TTL,然后使用新属性重新启用它。禁用后,TTL 将在大约 30 分钟内继续处理删除。必须对已恢复的表重新配置 TTL。

  5. (可选)您可以通过模拟到期日期和时间并匹配几个项目来执行测试。这为您提供了商品的样本列表,并确认有些商品包含提供的 TTL 属性名称以及过期时间。

启用 TTL 后,当您在 DynamoDB 控制台上查看项目时,TTL 属性会被标记为 TTL。您可以通过将指针悬停在属性上来查看项目过期的日期和时间。

Python

您可以使用UpdateTimeToLive操作使用代码启用 TTL。

import boto3 def enable_ttl(table_name, ttl_attribute_name): """ Enables TTL on DynamoDB table for a given attribute name on success, returns a status code of 200 on error, throws an exception :param table_name: Name of the DynamoDB table :param ttl_attribute_name: The name of the TTL attribute being provided to the table. """ try: dynamodb = boto3.client('dynamodb') # Enable TTL on an existing DynamoDB table response = dynamodb.update_time_to_live( TableName=table_name, TimeToLiveSpecification={ 'Enabled': True, 'AttributeName': ttl_attribute_name } ) # In the returned response, check for a successful status code. if response['ResponseMetadata']['HTTPStatusCode'] == 200: print("TTL has been enabled successfully.") else: print(f"Failed to enable TTL, status code {response['ResponseMetadata']['HTTPStatusCode']}") except Exception as ex: print("Couldn't enable TTL in table %s. Here's why: %s" % (table_name, ex)) raise # your values enable_ttl('your-table-name', 'expirationDate')

您可以使用描述表上的 TTL 状态的DescribeTimeToLive操作来确认 TTL 已启用。TimeToLive状态为ENABLEDDISABLED

# create a DynamoDB client dynamodb = boto3.client('dynamodb') # set the table name table_name = 'YourTable' # describe TTL response = dynamodb.describe_time_to_live(TableName=table_name)
Javascript

您可以使用UpdateTimeToLiveCommand操作使用代码启用 TTL。

import { DynamoDBClient, UpdateTimeToLiveCommand } from "@aws-sdk/client-dynamodb"; const enableTTL = async (tableName, ttlAttribute) => { const client = new DynamoDBClient({}); const params = { TableName: tableName, TimeToLiveSpecification: { Enabled: true, AttributeName: ttlAttribute } }; try { const response = await client.send(new UpdateTimeToLiveCommand(params)); if (response.$metadata.httpStatusCode === 200) { console.log(`TTL enabled successfully for table ${tableName}, using attribute name ${ttlAttribute}.`); } else { console.log(`Failed to enable TTL for table ${tableName}, response object: ${response}`); } return response; } catch (e) { console.error(`Error enabling TTL: ${e}`); throw e; } }; // call with your own values enableTTL('ExampleTable', 'exampleTtlAttribute');
  1. TTLExample 表上启用 TTL。

    aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
  2. TTLExample 表上描述 TTL。

    aws dynamodb describe-time-to-live --table-name TTLExample { "TimeToLiveDescription": { "AttributeName": "ttl", "TimeToLiveStatus": "ENABLED" } }
  3. 通过使用 BASH shell 和 TTLExample 设置存活时间属性将项目添加至 AWS CLI 表。

    EXP=`date -d '+5 days' +%s` aws dynamodb put-item --table-name "TTLExample" --item '{"id": {"N": "1"}, "ttl": {"N": "'$EXP'"}}'

此示例从当前日期开始,并在当前日期上增加 5 天来创建过期时间。然后,它将过期时间转换为纪元时间格式,以便最终添加项目到“TTLExample”表。

注意

为存活时间设置过期值的一种方式是计算添加到过期时间的秒数。例如,5 天是 432000 秒。但是,人们通常习惯于从某个日期算起。

获取当前时间的纪元时间格式非常简单,如下例中所示。

  • Linux 终端:date +%s

  • Python:import time; int(time.time())

  • Java:System.currentTimeMillis() / 1000L

  • JavaScript: Math.floor(Date.now() / 1000)

  1. TTLExample 表上启用 TTL。

    aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
  2. TTLExample 表上描述 TTL。

    aws dynamodb describe-time-to-live --table-name TTLExample { "TimeToLiveDescription": { "AttributeName": "ttl", "TimeToLiveStatus": "ENABLED" } }
  3. 通过使用 BASH shell 和 TTLExample 设置存活时间属性将项目添加至 AWS CLI 表。

    EXP=`date -d '+5 days' +%s` aws dynamodb put-item --table-name "TTLExample" --item '{"id": {"N": "1"}, "ttl": {"N": "'$EXP'"}}'

此示例从当前日期开始,并在当前日期上增加 5 天来创建过期时间。然后,它将过期时间转换为纪元时间格式,以便最终添加项目到“TTLExample”表。

注意

为存活时间设置过期值的一种方式是计算添加到过期时间的秒数。例如,5 天是 432000 秒。但是,人们通常习惯于从某个日期算起。

获取当前时间的纪元时间格式非常简单,如下例中所示。

  • Linux 终端:date +%s

  • Python:import time; int(time.time())

  • Java:System.currentTimeMillis() / 1000L

  • JavaScript: Math.floor(Date.now() / 1000)