如何編碼 BatchWriteItemRequest 並儲存資料

private static void saveItem(List<EventTracker> items) {
    List<WriteRequest> wrList = new ArrayList<>();
    try {

        for (EventTracker item : items) {
            WriteRequest wreqItem;
            wreqItem = getWriteRequest(item);
            wrList.add(wreqItem);
        }

        try {

            BatchWriteItemResult batchWriteItemResult = new BatchWriteItemResult();
            do {
                BatchWriteItemRequest batchWriteItemRequest = new BatchWriteItemRequest();
                batchWriteItemRequest.addRequestItemsEntry(forumTableName, wrList);// setRequestItems(writeRequestitems);
                batchWriteItemResult = amazonDynamoDB.batchWriteItem(batchWriteItemRequest);
                // Check for unprocessed keys which could happen if you
                // exceed
                // provisioned throughput
                Map<String, List<WriteRequest>> unprocessedItems = batchWriteItemResult.getUnprocessedItems();
                if (unprocessedItems.size() == 0) {
                    System.out.println("No unprocessed items found");
                } else {
                    System.out.println("Sleeping for: " + ThreadLocalRandom.current().nextInt(500, 999 + 1));
                    Thread.sleep(ThreadLocalRandom.current().nextInt(500, 999 + 1));
                    wrList = unprocessedItems.get(forumTableName);
                    System.out.println("Retrieving the unprocessed items");
                }

            } while (batchWriteItemResult.getUnprocessedItems().size() > 0);

        } catch (Exception e) {
            System.err.println("Failed to retrieve items: ");
            e.printStackTrace(System.err);
        }

    } catch (Exception e) {

    }
}

如果我們想要使用批處理操作將資料放入 dynamo db 表,我們需要知道這一點。讓我們看看完成此任務需要遵循的步驟。在這個例子中,我們試圖保留一個 EventTracker 資料列表,這是我的 POJO。

  1. 對於要插入的每條記錄,我們需要建立一個 PUT 請求。
  2. 每個 PUT 請求都包含在寫請求中。
  3. 所有寫請求都繫結在一個列表中。
  4. 然後將 WriteRequest 列表新增到 BatchWriteItemRequest 並執行。

下面的程式碼將顯示我們如何建立寫請求。