

# 在 DynamoDB 中启用生存时间（TTL）
<a name="time-to-live-ttl-how-to"></a>

**注意**  
为了协助调试 TTL 功能和验证该功能是否正常运行，为项目 TTL 提供的值将以纯文本形式记录在 DynamoDB 诊断日志中。

您可以在 Amazon DynamoDB 控制台中，在 Amazon Command Line Interface（Amazon CLI）中，或者对于任何支持的 Amazon SDK 使用 [Amazon DynamoDB API 参考](https://docs.amazonaws.cn/amazondynamodb/latest/APIReference/)，来启用 TTL。在所有分区中启用 TTL 大约需要一个小时。

## 使用 Amazon 控制台启用 DynamoDB TTL
<a name="time-to-live-ttl-how-to-enable-console"></a>

1. 登录 Amazon Web Services 管理控制台，打开 DynamoDB 控制台：[https://console.aws.amazon.com/dynamodb/](https://console.amazonaws.cn/dynamodb/)。

1. 选择**表**，然后选择您要修改的表。

1. 在**其它设置**选项卡的**生存时间(TTL)** 部分中，选择**开启**来启用 TTL。

1. 在表上启用 TTL 时，DynamoDB 要求您标识此服务在确定项目是否符合过期条件时将查找的特定属性名称。如下所示的 TTL 属性名称区分大小写，并且必须与读取和写入操作中定义的属性相匹配。不匹配将导致已过期的项目被取消删除。重命名 TTL 属性需要您禁用 TTL，然后使用新属性重新启用它。禁用后，TTL 将在大约 30 分钟内继续处理删除。必须对已恢复的表重新配置 TTL。  
![区分大小写的 TTL 属性名称，DynamoDB 使用该属性来确定项目是否符合过期条件。](http://docs.amazonaws.cn/amazondynamodb/latest/developerguide/images/EnableTTL-Settings.png)

1. （可选）您可以通过模拟过期日期和时间并匹配几个项目来执行测试。这为您提供了项目的样本列表，并确认有些项目包含随过期时间提供的 TTL 属性名称。

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

## 使用 API 启用 DynamoDB TTL
<a name="time-to-live-ttl-how-to-enable-api"></a>

------
#### [ Python ]

您可以使用 [UpdateTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/update_time_to_live.html) 操作通过代码启用 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')
```

您可以使用 [DescribeTimeToLive](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb/client/describe_time_to_live.html) 操作确认 TTL 已启用，该操作描述了表上的 TTL 状态。`TimeToLive` 状态为 `ENABLED` 或 `DISABLED`。

```
# 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](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-dynamodb/Class/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');
```

------

## 使用 Amazon CLI 启用生存时间
<a name="time-to-live-ttl-how-to-enable-cli-sdk"></a>

1. 在 `TTLExample` 表上启用 TTL。

   ```
   aws dynamodb update-time-to-live --table-name TTLExample --time-to-live-specification "Enabled=true, AttributeName=ttl"
   ```

1. 在 `TTLExample` 表上描述 TTL。

   ```
   aws dynamodb describe-time-to-live --table-name TTLExample
   {
       "TimeToLiveDescription": {
           "AttributeName": "ttl",
           "TimeToLiveStatus": "ENABLED"
       }
   }
   ```

1. 通过使用 BASH shell 和 `TTLExample` 设置生存时间属性将项目添加至 Amazon 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)`

## 使用 Amazon CloudFormation 启用 DynamoDB TTL
<a name="time-to-live-ttl-how-to-enable-cf"></a>

```
AWSTemplateFormatVersion: "2010-09-09"
Resources:
  TTLExampleTable:
    Type: AWS::DynamoDB::Table
    Description: "A DynamoDB table with TTL Specification enabled"
    Properties:
      AttributeDefinitions:
        - AttributeName: "Album"
          AttributeType: "S"
        - AttributeName: "Artist"
          AttributeType: "S"
      KeySchema:
        - AttributeName: "Album"
          KeyType: "HASH"
        - AttributeName: "Artist"
          KeyType: "RANGE"
      ProvisionedThroughput:
        ReadCapacityUnits: "5"
        WriteCapacityUnits: "5"
      TimeToLiveSpecification:
        AttributeName: "TTLExampleAttribute"
        Enabled: true
```

可以在[此处](https://docs.amazonaws.cn/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-table-timetolivespecification.html)找到有关在 Amazon CloudFormation 模板中使用 TTL 的更多详细信息。