기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
컴퓨팅 타임 투 라이프 (TTL)
TTL을 구현하는 일반적인 방법은 항목이 생성되거나 마지막으로 업데이트된 시기를 기준으로 항목의 만료 시간을 설정하는 것입니다. 이를 위해서는 createdAt
및 updatedAt
타임스탬프에 시간을 추가하면 됩니다. 예를 들어 새로 생성한 항목의 TTL을 createdAt
+90일로 설정할 수 있습니다. 항목이 업데이트되면 TTL을 +90일로 다시 계산할 수 있습니다. updatedAt
계산된 만료 시간은 에포크 형식 (초) 이어야 합니다. 만료 및 삭제 대상으로 간주되려면 TTL은 과거 5년을 초과할 수 없습니다. 다른 형식을 사용하는 경우 TTL 프로세스는 해당 항목을 무시합니다. 만료 날짜를 항목을 만료하려는 미래 날짜로 설정하면 해당 기간이 지나면 항목이 만료됩니다. 예를 들어 만료 날짜를 1724241326 (2024년 8월 21일 월요일 11:55:26 (GMT)) 으로 설정했다고 가정해 보겠습니다. 지정된 시간이 지나면 아이템이 만료됩니다.
항목을 생성하고 Time to Live (Time to Live) 를 설정합니다.
다음 예제는 TTL 속성 expireAt
이름으로 사용하여 새 항목을 만들 때 만료 시간을 계산하는 방법을 보여줍니다. 대입문은 현재 시간을 변수로 가져옵니다. 이 예시에서는 만료 시간을 현재 시간으로부터 90일로 계산합니다. 그러면 시간이 에포크 형식으로 변환되고 TTL 속성에 정수 데이터 유형으로 저장됩니다.
- Python
-
import boto3
from datetime import datetime, timedelta
def create_dynamodb_item(table_name, region, primary_key, sort_key):
"""
Creates a DynamoDB item with an attached expiry attribute.
:param table_name: Table name for the boto3 resource to target when creating an item
:param region: string representing the AWS region. Example: `us-east-1`
:param primary_key: one attribute known as the partition key.
:param sort_key: Also known as a range attribute.
:return: Void (nothing)
"""
try:
dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table(table_name)
# Get the current time in epoch second format
current_time = int(datetime.now().timestamp())
# Calculate the expiration time (90 days from now) in epoch second format
expiration_time = int((datetime.now() + timedelta(days=90)).timestamp())
item = {
'primaryKey': primary_key,
'sortKey': sort_key,
'createdAt': current_time,
'expiredAt': expiration_time
}
table.put_item(Item=item)
print("Item created successfully.")
except Exception as e:
print(f"Error creating item: {e}")
raise
# Use your own values
create_dynamodb_item('your-table-name', 'us-west-2', 'your-partition-key-value', 'your-sort-key-value')
- Javascript
-
이 요청에는 새로 만든 항목의 만료 시간을 계산하는 로직을 추가합니다.
import { DynamoDBClient, PutItemCommand } from "@aws-sdk/client-dynamodb";
function createDynamoDBItem(table_name, region, partition_key, sort_key) {
const client = new DynamoDBClient({
region: region,
endpoint: `https://dynamodb.${region}.amazonaws.com`
});
// Get the current time in epoch second format
const current_time = Math.floor(new Date().getTime() / 1000);
// Calculate the expireAt time (90 days from now) in epoch second format
const expire_at = Math.floor((new Date().getTime() + 90 * 24 * 60 * 60 * 1000) / 1000);
// Create DynamoDB item
const item = {
'partitionKey': {'S': partition_key},
'sortKey': {'S': sort_key},
'createdAt': {'N': current_time.toString()},
'expireAt': {'N': expire_at.toString()}
};
const putItemCommand = new PutItemCommand({
TableName: table_name,
Item: item,
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1,
},
});
client.send(putItemCommand, function(err, data) {
if (err) {
console.log("Exception encountered when creating item %s, here's what happened: ", data, ex);
throw err;
} else {
console.log("Item created successfully: %s.", data);
return data;
}
});
}
// use your own values
createDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');
항목을 업데이트하고 Time to Live를 새로 고침하세요.
이 예제는 이전 섹션의 예제에 이어 나온 것입니다. 항목이 업데이트되면 만료 시간을 다시 계산할 수 있습니다. 다음 예제에서는 expireAt
타임스탬프를 현재 시간으로부터 90일이 되도록 다시 계산합니다.
- Python
-
import boto3
from datetime import datetime, timedelta
def update_dynamodb_item(table_name, region, primary_key, sort_key):
"""
Update an existing DynamoDB item with a TTL.
:param table_name: Name of the DynamoDB table
:param region: AWS Region of the table - example `us-east-1`
:param primary_key: one attribute known as the partition key.
:param sort_key: Also known as a range attribute.
:return: Void (nothing)
"""
try:
# Create the DynamoDB resource.
dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table(table_name)
# Get the current time in epoch second format
current_time = int(datetime.now().timestamp())
# Calculate the expireAt time (90 days from now) in epoch second format
expire_at = int((datetime.now() + timedelta(days=90)).timestamp())
table.update_item(
Key={
'partitionKey': primary_key,
'sortKey': sort_key
},
UpdateExpression="set updatedAt=:c, expireAt=:e",
ExpressionAttributeValues={
':c': current_time,
':e': expire_at
},
)
print("Item updated successfully.")
except Exception as e:
print(f"Error updating item: {e}")
# Replace with your own values
update_dynamodb_item('your-table-name', 'us-west-2', 'your-partition-key-value', 'your-sort-key-value')
업데이트 작업의 출력은 시간은 변경되지 않았지만 updatedAt
및 createdAt
expireAt
시간은 업데이트되었음을 보여줍니다. 이제 expireAt
시간은 마지막 업데이트 시점인 2023년 10월 19일 목요일 오후 1:27:15 로부터 90일로 설정되었습니다.
partition_key |
createdAt |
updatedAt |
만료 날짜 |
속성_1 |
속성_2 |
일부_값
|
2023-07-17 14:11:05.322 323 |
2023-07-19 13:27:15.213 423 |
1697722035 |
새 값 |
어느 정도_가치 |
- Javascript
-
import { DynamoDBClient, UpdateItemCommand } from "@aws-sdk/client-dynamodb";
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
async function updateDynamoDBItem(tableName, region, partitionKey, sortKey) {
const client = new DynamoDBClient({
region: region,
endpoint: `https://dynamodb.${region}.amazonaws.com`
});
const currentTime = Math.floor(Date.now() / 1000);
const expireAt = Math.floor((Date.now() + 90 * 24 * 60 * 60 * 1000) / 1000); ////is there a better way to do this?
const params = {
TableName: tableName,
Key: marshall({
partitionKey: partitionKey,
sortKey: sortKey
}),
UpdateExpression: "SET updatedAt = :c, expireAt = :e",
ExpressionAttributeValues: marshall({
":c": currentTime,
":e": expireAt
}),
};
try {
const data = await client.send(new UpdateItemCommand(params));
const responseData = unmarshall(data.Attributes);
console.log("Item updated successfully: %s", responseData);
return responseData;
} catch (err) {
console.error("Error updating item:", err);
throw err;
}
}
//enter your values here
updateDynamoDBItem('your-table-name', 'us-east-1', 'your-partition-key-value', 'your-sort-key-value');
이 소개에서 설명하는 TTL 예제는 최근에 업데이트된 항목만 테이블에 보관하도록 하는 방법을 보여줍니다. 업데이트된 항목은 수명이 연장되는 반면, 업데이트되지 않은 항목은 생성 후 만료되고 비용 없이 삭제되므로 저장 공간이 줄어들고 정리된 테이블이 유지 관리됩니다.