예: AWS SDK for Java 문서 API를 사용하여 이진 형식 속성 처리 - Amazon DynamoDB

예: AWS SDK for Java 문서 API를 사용하여 이진 형식 속성 처리

다음은 이진 형식 속성의 처리를 설명하는 Java 코드 예제입니다. 이 예제에서는 항목을 Reply 테이블에 추가합니다. 추가된 항목에는 압축 데이터가 저장된 이진수 형식의 속성(ExtendedMessage)이 포함되어 있습니다. 그런 다음 항목을 가져와서 모든 속성 값을 출력합니다. 이해를 돕기 위해 예제에서는 GZIPOutputStream 클래스를 사용해 샘플 스트림을 압축하여 ExtendedMessage 속성에 할당합니다. 이진 속성을 검색하면 GZIPInputStream 클래스를 사용하여 이 속성의 압축이 풀립니다.

참고

또한 SDK for Java에서는 객체 지속성 모델을 제공하므로 DynamoDB 테이블로 클라이언트 측 클래스를 매핑할 수 있습니다. 이러한 접근 방식을 활용하면 작성해야 할 코드가 줄어듭니다. 자세한 내용은 Java 1.x: DynamoDBMapper 단원을 참조하십시오.

DynamoDB에서 테이블 생성 및 코드 예시에 대한 데이터 로드 단원을 따랐다면 이미 Reply 테이블이 생성되어 있습니다. 이 테이블을 프로그래밍 방식으로 생성할 수도 있습니다. 자세한 내용은 AWS SDK for Java를 사용한 예시 테이블 생성 및 데이터 업로드 단원을 참조하십시오.

다음 샘플을 테스트하기 위한 단계별 지침은 Java 코드 예 섹션을 참조하세요.

package com.amazonaws.codesamples.document; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; 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.document.spec.GetItemSpec; public class DocumentAPIItemBinaryExample { static AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); static DynamoDB dynamoDB = new DynamoDB(client); static String tableName = "Reply"; static SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); public static void main(String[] args) throws IOException { try { // Format the primary key values String threadId = "Amazon DynamoDB#DynamoDB Thread 2"; dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); String replyDateTime = dateFormatter.format(new Date()); // Add a new reply with a binary attribute type createItem(threadId, replyDateTime); // Retrieve the reply with a binary attribute type retrieveItem(threadId, replyDateTime); // clean up by deleting the item deleteItem(threadId, replyDateTime); } catch (Exception e) { System.err.println("Error running the binary attribute type example: " + e); e.printStackTrace(System.err); } } public static void createItem(String threadId, String replyDateTime) throws IOException { Table table = dynamoDB.getTable(tableName); // Craft a long message String messageInput = "Long message to be compressed in a lengthy forum reply"; // Compress the long message ByteBuffer compressedMessage = compressString(messageInput.toString()); table.putItem(new Item().withPrimaryKey("Id", threadId).withString("ReplyDateTime", replyDateTime) .withString("Message", "Long message follows").withBinary("ExtendedMessage", compressedMessage) .withString("PostedBy", "User A")); } public static void retrieveItem(String threadId, String replyDateTime) throws IOException { Table table = dynamoDB.getTable(tableName); GetItemSpec spec = new GetItemSpec().withPrimaryKey("Id", threadId, "ReplyDateTime", replyDateTime) .withConsistentRead(true); Item item = table.getItem(spec); // Uncompress the reply message and print String uncompressed = uncompressString(ByteBuffer.wrap(item.getBinary("ExtendedMessage"))); System.out.println("Reply message:\n" + " Id: " + item.getString("Id") + "\n" + " ReplyDateTime: " + item.getString("ReplyDateTime") + "\n" + " PostedBy: " + item.getString("PostedBy") + "\n" + " Message: " + item.getString("Message") + "\n" + " ExtendedMessage (uncompressed): " + uncompressed + "\n"); } public static void deleteItem(String threadId, String replyDateTime) { Table table = dynamoDB.getTable(tableName); table.deleteItem("Id", threadId, "ReplyDateTime", replyDateTime); } private static ByteBuffer compressString(String input) throws IOException { // Compress the UTF-8 encoded String into a byte[] ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream os = new GZIPOutputStream(baos); os.write(input.getBytes("UTF-8")); os.close(); baos.close(); byte[] compressedBytes = baos.toByteArray(); // The following code writes the compressed bytes to a ByteBuffer. // A simpler way to do this is by simply calling // ByteBuffer.wrap(compressedBytes); // However, the longer form below shows the importance of resetting the // position of the buffer // back to the beginning of the buffer if you are writing bytes directly // to it, since the SDK // will consider only the bytes after the current position when sending // data to DynamoDB. // Using the "wrap" method automatically resets the position to zero. ByteBuffer buffer = ByteBuffer.allocate(compressedBytes.length); buffer.put(compressedBytes, 0, compressedBytes.length); buffer.position(0); // Important: reset the position of the ByteBuffer // to the beginning return buffer; } private static String uncompressString(ByteBuffer input) throws IOException { byte[] bytes = input.array(); ByteArrayInputStream bais = new ByteArrayInputStream(bytes); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPInputStream is = new GZIPInputStream(bais); int chunkSize = 1024; byte[] buffer = new byte[chunkSize]; int length = 0; while ((length = is.read(buffer, 0, chunkSize)) != -1) { baos.write(buffer, 0, length); } String result = new String(baos.toByteArray(), "UTF-8"); is.close(); baos.close(); bais.close(); return result; } }