TryDaxHelper.java - Amazon DynamoDB

TryDaxHelper.java

El archivo TryDaxHelper.java contiene métodos de utilidad.

Los métodos getDynamoDBClient y getDaxClient proporcionan clientes de Amazon DynamoDB y DynamoDB Accelerator (DAX). Para las operaciones del plano de control (CreateTable, DeleteTable) y las operaciones de escritura, el programa utiliza el cliente de DynamoDB. Si especifica el punto de enlace de un clúster de DAX, el programa principal crea un cliente de DAX para llevar a cabo las operaciones de lectura (GetItem, Query, Scan).

Los demás métodos de TryDaxHelper (createTable, writeData y deleteTable) se utilizan para configurar y eliminar la tabla de DynamoDB y sus datos.

Puede modificar el programa de varias maneras:

  • Utilizar unos ajustes de desempeño provisionado diferentes para la tabla.

  • Modificar el tamaño de cada elemento escrito (consulte la variable stringSize del método writeData).

  • Modificar el número de pruebas de GetItem, Query y Scan y sus parámetros.

  • Marcar como comentarios las líneas que contienen helper.CreateTable y helper.DeleteTable, sin no desea crear y eliminar la tabla cada vez que ejecute el programa.

nota

Para ejecutar este programa, puede configurar Maven para usar el cliente para el SDK de DAX para Java y AWS SDK for Java como dependencias. Para obtener más información, consulte Uso del cliente como dependencia de Apache Maven.

O, puede descargar e incluir el cliente Java de DAX y el AWS SDK for Java en su classpath. Consulte Java y DAX para ver un ejemplo de cómo establecer la variable CLASSPATH.

import com.amazon.dax.client.dynamodbv2.AmazonDaxClientBuilder; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.Item; import com.amazonaws.services.dynamodbv2.document.Table; import com.amazonaws.services.dynamodbv2.model.AttributeDefinition; import com.amazonaws.services.dynamodbv2.model.KeySchemaElement; import com.amazonaws.services.dynamodbv2.model.KeyType; import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput; import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType; import com.amazonaws.util.EC2MetadataUtils; public class TryDaxHelper { private static final String region = EC2MetadataUtils.getEC2InstanceRegion(); DynamoDB getDynamoDBClient() { System.out.println("Creating a DynamoDB client"); AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard() .withRegion(region) .build(); return new DynamoDB(client); } DynamoDB getDaxClient(String daxEndpoint) { System.out.println("Creating a DAX client with cluster endpoint " + daxEndpoint); AmazonDaxClientBuilder daxClientBuilder = AmazonDaxClientBuilder.standard(); daxClientBuilder.withRegion(region).withEndpointConfiguration(daxEndpoint); AmazonDynamoDB client = daxClientBuilder.build(); return new DynamoDB(client); } void createTable(String tableName, DynamoDB client) { Table table = client.getTable(tableName); try { System.out.println("Attempting to create table; please wait..."); table = client.createTable(tableName, Arrays.asList( new KeySchemaElement("pk", KeyType.HASH), // Partition key new KeySchemaElement("sk", KeyType.RANGE)), // Sort key Arrays.asList( new AttributeDefinition("pk", ScalarAttributeType.N), new AttributeDefinition("sk", ScalarAttributeType.N)), new ProvisionedThroughput(10L, 10L)); table.waitForActive(); System.out.println("Successfully created table. Table status: " + table.getDescription().getTableStatus()); } catch (Exception e) { System.err.println("Unable to create table: "); e.printStackTrace(); } } void writeData(String tableName, DynamoDB client, int pkmax, int skmax) { Table table = client.getTable(tableName); System.out.println("Writing data to the table..."); int stringSize = 1000; StringBuilder sb = new StringBuilder(stringSize); for (int i = 0; i < stringSize; i++) { sb.append('X'); } String someData = sb.toString(); try { for (Integer ipk = 1; ipk <= pkmax; ipk++) { System.out.println(("Writing " + skmax + " items for partition key: " + ipk)); for (Integer isk = 1; isk <= skmax; isk++) { table.putItem(new Item() .withPrimaryKey("pk", ipk, "sk", isk) .withString("someData", someData)); } } } catch (Exception e) { System.err.println("Unable to write item:"); e.printStackTrace(); } } void deleteTable(String tableName, DynamoDB client) { Table table = client.getTable(tableName); try { System.out.println("\nAttempting to delete table; please wait..."); table.delete(); table.waitForDelete(); System.out.println("Successfully deleted table."); } catch (Exception e) { System.err.println("Unable to delete table: "); e.printStackTrace(); } } }