Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
在 Java 中使用 DynamoDB 表
您可以使用 Amazon SDK for Java 创建、更新和删除 Amazon DynamoDB 表,以及列出您账户中所有的表或者获取有关某个特定表的信息。
创建表
要创建表,您必须提供表名称、表的主键以及预置的吞吐量值。下面的代码段会创建一个将数字类型属性 ID 用作主键的示例表。
要使用 Amazon SDK for Java API 创建表
-
创建 DynamoDB
类的实例。
-
实例化 CreateTableRequest
以提供请求信息。
您必须提供表名称、属性定义、键架构以及预置吞吐量值。
-
以参数形式提供请求对象,运行 createTable
方法。
以下代码示例演示了上述步骤。
- Java 2.x
-
import software.amazon.awssdk.core.waiters.WaiterResponse;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.dynamodb.DynamoDbClient;
import software.amazon.awssdk.services.dynamodb.model.AttributeDefinition;
import software.amazon.awssdk.services.dynamodb.model.CreateTableRequest;
import software.amazon.awssdk.services.dynamodb.model.CreateTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableRequest;
import software.amazon.awssdk.services.dynamodb.model.DescribeTableResponse;
import software.amazon.awssdk.services.dynamodb.model.DynamoDbException;
import software.amazon.awssdk.services.dynamodb.model.KeySchemaElement;
import software.amazon.awssdk.services.dynamodb.model.KeyType;
import software.amazon.awssdk.services.dynamodb.model.ProvisionedThroughput;
import software.amazon.awssdk.services.dynamodb.model.ScalarAttributeType;
import software.amazon.awssdk.services.dynamodb.waiters.DynamoDbWaiter;
/**
* Before running this Java V2 code example, set up your development
* environment, including your credentials.
*
* For more information, see the following documentation topic:
*
* https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
*/
public class CreateTable {
public static void main(String[] args) {
final String usage = """
Usage:
<tableName> <key>
Where:
tableName - The Amazon DynamoDB table to create (for example, Music3).
key - The key for the Amazon DynamoDB table (for example, Artist).
""";
if (args.length != 2) {
System.out.println(usage);
System.exit(1);
}
String tableName = args[0];
String key = args[1];
System.out.println("Creating an Amazon DynamoDB table " + tableName + " with a simple primary key: " + key);
Region region = Region.US_EAST_1;
DynamoDbClient ddb = DynamoDbClient.builder()
.region(region)
.build();
String result = createTable(ddb, tableName, key);
System.out.println("New table is " + result);
ddb.close();
}
public static String createTable(DynamoDbClient ddb, String tableName, String key) {
DynamoDbWaiter dbWaiter = ddb.waiter();
CreateTableRequest request = CreateTableRequest.builder()
.attributeDefinitions(AttributeDefinition.builder()
.attributeName(key)
.attributeType(ScalarAttributeType.S)
.build())
.keySchema(KeySchemaElement.builder()
.attributeName(key)
.keyType(KeyType.HASH)
.build())
.provisionedThroughput(ProvisionedThroughput.builder()
.readCapacityUnits(10L)
.writeCapacityUnits(10L)
.build())
.tableName(tableName)
.build();
String newTable;
try {
CreateTableResponse response = ddb.createTable(request);
DescribeTableRequest tableRequest = DescribeTableRequest.builder()
.tableName(tableName)
.build();
// Wait until the Amazon DynamoDB table is created.
WaiterResponse<DescribeTableResponse> waiterResponse = dbWaiter.waitUntilTableExists(tableRequest);
waiterResponse.matched().response().ifPresent(System.out::println);
newTable = response.tableDescription().tableName();
return newTable;
} catch (DynamoDbException e) {
System.err.println(e.getMessage());
System.exit(1);
}
return "";
}
}
- Java
-
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);
List<AttributeDefinition> attributeDefinitions= new ArrayList<AttributeDefinition>();
attributeDefinitions.add(new AttributeDefinition().withAttributeName("Id").withAttributeType("N"));
List<KeySchemaElement> keySchema = new ArrayList<KeySchemaElement>();
keySchema.add(new KeySchemaElement().withAttributeName("Id").withKeyType(KeyType.HASH));
CreateTableRequest request = new CreateTableRequest()
.withTableName(tableName)
.withKeySchema(keySchema)
.withAttributeDefinitions(attributeDefinitions)
.withProvisionedThroughput(new ProvisionedThroughput()
.withReadCapacityUnits(5L)
.withWriteCapacityUnits(6L));
Table table = dynamoDB.createTable(request);
table.waitForActive();
在 DynamoDB 创建表并且将其状态设置为 ACTIVE 之前,表将无法使用。createTable
请求返回 Table
对象,您可以用它来获取有关表的更多信息。
例
TableDescription tableDescription =
dynamoDB.getTable(tableName).describe();
System.out.printf("%s: %s \t ReadCapacityUnits: %d \t WriteCapacityUnits: %d",
tableDescription.getTableStatus(),
tableDescription.getTableName(),
tableDescription.getProvisionedThroughput().getReadCapacityUnits(),
tableDescription.getProvisionedThroughput().getWriteCapacityUnits());
您可以随时调用客户端的 describe
方法来获取表信息。
例
TableDescription tableDescription = dynamoDB.getTable(tableName).describe();
更新表
您可以仅更新现有表的预置吞吐量值。您可能需要根据应用程序的要求更新这些值。
使用Amazon SDK for Java API 更新表
-
创建 Table
类的实例。
-
创建 ProvisionedThroughput
类的实例以提供新吞吐量值。
-
提供 ProvisionedThroughput
实例作为参数来执行 updateTable
方法。
以下代码示例演示了上述步骤。
例
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("ProductCatalog");
ProvisionedThroughput provisionedThroughput = new ProvisionedThroughput()
.withReadCapacityUnits(15L)
.withWriteCapacityUnits(12L);
table.updateTable(provisionedThroughput);
table.waitForActive();
删除表
使用Amazon SDK for Java API 删除表
-
创建 Table
类的实例。
-
创建一个 DeleteTableRequest
类的实例,并提供您想要删除的表的名称。
-
提供 Table
实例作为参数来执行 deleteTable
方法。
以下代码示例演示了上述步骤。
例
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);
Table table = dynamoDB.getTable("ProductCatalog");
table.delete();
table.waitForDelete();
列出表
要列出您账户中的表,请创建 DynamoDB
的实例并执行 listTables
方法。ListTables 操作无需使用参数。
例
AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build();
DynamoDB dynamoDB = new DynamoDB(client);
TableCollection<ListTablesResult> tables = dynamoDB.listTables();
Iterator<Table> iterator = tables.iterator();
while (iterator.hasNext()) {
Table table = iterator.next();
System.out.println(table.getTableName());
}