本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
常見的實作方法是根據項目的建立時間或上次更新時間來TTL設定項目的過期時間。這可以透過將時間新增至 createdAt
和 updatedAt
時間戳記來完成。例如,新建立項目TTL的 可以設定為 createdAt
+ 90 天。當項目更新時, TTL可以重新計算為 updatedAt
+ 90 天。
計算的過期時間必須是 epoch 格式,以秒為單位。若要考慮過期和刪除, 在過去TTL不得超過五年。如果您使用任何其他格式,TTL程序會忽略項目。如果您將過期日期設定為您希望項目過期的未來某個時間,則該項目將在該時間之後過期。例如,假設您將過期日期設定為 1724241326 (即 2024 年 8 月 21 日星期一 11:55:26 (GMT))。項目將在指定的時間之後過期。
建立項目並設定存留時間
下列範例示範如何在建立新項目時使用 expireAt
做為TTL屬性名稱來計算過期時間。指派陳述式會取得目前時間做為變數。在此範例中,過期時間的計算方式為目前時間的 90 天。然後,時間會轉換為 epoch 格式,並在 TTL 屬性中儲存為整數資料類型。
下列程式碼範例示範如何使用 建立項目TTL。
- SDK 適用於 Java 2.x
-
package com.amazon.samplelib.ttl; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.PutItemRequest; import software.amazon.awssdk.services.dynamodb.model.PutItemResponse; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.utils.ImmutableMap; import java.io.Serializable; import java.util.Map; import java.util.Optional; public class CreateTTL { public static void main(String[] args) { final String usage = """ Usage: <tableName> <primaryKey> <sortKey> <region> Where: tableName - The Amazon DynamoDB table being queried. primaryKey - The name of the primary key. Also known as the hash or partition key. sortKey - The name of the sort key. Also known as the range attribute. region (optional) - The AWS region that the Amazon DynamoDB table is located in. (Default: us-east-1) """; // Optional "region" parameter - if args list length is NOT 3 or 4, short-circuit exit. if (!(args.length == 3 || args.length == 4)) { System.out.println(usage); System.exit(1); } String tableName = args[0]; String primaryKey = args[1]; String sortKey = args[2]; Region region = Optional.ofNullable(args[3]).isEmpty() ? Region.US_EAST_1 : Region.of(args[3]); // Get current time in epoch second format final long createDate = System.currentTimeMillis() / 1000; // Calculate expiration time 90 days from now in epoch second format final long expireDate = createDate + (90 * 24 * 60 * 60); final ImmutableMap<String, ? extends Serializable> itemMap = ImmutableMap.of("primaryKey", primaryKey, "sortKey", sortKey, "creationDate", createDate, "expireAt", expireDate); final PutItemRequest request = PutItemRequest.builder() .tableName(tableName) .item((Map<String, AttributeValue>) itemMap) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final PutItemResponse response = ddb.putItem(request); System.out.println(tableName + " PutItem operation with TTL successful. Request id is " + response.responseMetadata().requestId()); } catch (ResourceNotFoundException e) { System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.exit(0); } }
-
如需API詳細資訊,請參閱 AWS SDK for Java 2.x API 參考PutItem中的 。
-
更新項目並重新整理存留時間
此範例是上一節的接續範例。如果項目已更新,則可以重新計算過期時間。下列範例會將expireAt
時間戳記重新計算為目前時間的 90 天。
下列程式碼範例示範如何更新項目的 TTL。
- SDK 適用於 Java 2.x
-
資料表中現有 DynamoDB 項目TTL的更新。
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.DynamoDbException; import software.amazon.awssdk.services.dynamodb.model.ResourceNotFoundException; import software.amazon.awssdk.services.dynamodb.model.UpdateItemRequest; import software.amazon.awssdk.services.dynamodb.model.UpdateItemResponse; import software.amazon.awssdk.utils.ImmutableMap; import java.util.Map; import java.util.Optional; // Get current time in epoch second format final long currentTime = System.currentTimeMillis() / 1000; // Calculate expiration time 90 days from now in epoch second format final long expireDate = currentTime + (90 * 24 * 60 * 60); // An expression that defines one or more attributes to be updated, the action to be performed on them, and new values for them. final String updateExpression = "SET updatedAt=:c, expireAt=:e"; final ImmutableMap<String, AttributeValue> keyMap = ImmutableMap.of("primaryKey", AttributeValue.fromS(primaryKey), "sortKey", AttributeValue.fromS(sortKey)); final Map<String, AttributeValue> expressionAttributeValues = ImmutableMap.of( ":c", AttributeValue.builder().s(String.valueOf(currentTime)).build(), ":e", AttributeValue.builder().s(String.valueOf(expireDate)).build() ); final UpdateItemRequest request = UpdateItemRequest.builder() .tableName(tableName) .key(keyMap) .updateExpression(updateExpression) .expressionAttributeValues(expressionAttributeValues) .build(); try (DynamoDbClient ddb = DynamoDbClient.builder() .region(region) .build()) { final UpdateItemResponse response = ddb.updateItem(request); System.out.println(tableName + " UpdateItem operation with TTL successful. Request id is " + response.responseMetadata().requestId()); } catch (ResourceNotFoundException e) { System.err.format("Error: The Amazon DynamoDB table \"%s\" can't be found.\n", tableName); System.exit(1); } catch (DynamoDbException e) { System.err.println(e.getMessage()); System.exit(1); } System.exit(0);
-
如需API詳細資訊,請參閱 AWS SDK for Java 2.x API 參考UpdateItem中的 。
-
本簡介中討論TTL的範例示範了一種方法,以確保僅將最近更新的項目保留在資料表中。更新的項目會延長其生命週期,而未更新的項目會在建立後過期,並且會免費刪除,從而減少儲存和維護乾淨的資料表。