

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 DynamoDB Auto Scaling 功能自動管理輸送容量
<a name="AutoScaling"></a>

許多資料庫工作負載本來就具週期性且難以事先預測。例如，假設有一個社交聯網應用程式，其中大部分使用者會在日間活動。資料庫必須能夠處理日間活動，但夜間則不需要同樣多的輸送量。又例如，請設想一下正被快速採用的新行動遊戲應用程式。如果遊戲變得太熱門，可能會超過可用的資料庫資源，而導致效能變慢及客戶不滿意。這類工作負載通常需要手動介入來擴展或縮減資料庫資源，以回應不斷改變的用量。

Amazon DynamoDB Auto Scaling 使用 AWS Application Auto Scaling 服務代表您動態調整佈建輸送量容量，以回應實際的流量模式。這使資料表或全域次要索引 (GSI) 能增加其佈建讀寫容量，在流量突增時處理請求而不被限流。當工作負載降低時，Application Auto Scaling 可降低輸送量，讓您無須為未使用的佈建容量付費。

**注意**  
如果您使用 AWS 管理主控台 建立資料表或全域次要索引，預設會啟用 DynamoDB Auto Scaling。您可隨時修改自動擴展設定。如需詳細資訊，請參閱[AWS 管理主控台 搭配 DynamoDB Auto Scaling 使用](AutoScaling.Console.md)。  
刪除資料表或全域資料表複本時，任何相關聯的可擴展目標、擴展政策或 CloudWatch 警示都不會跟著自動刪除。

使用 Application Auto Scaling，您就可以為資料表或全域次要索引建立*擴展政策*。調整規模政策可指定您要擴展讀取容量或寫入容量 (或兩者)，也可為資料表或索引指定最大與最小佈建容量單位設定。

調整規模政策也包含*目標使用率*：即在某個時間點耗用的佈建輸送量百分比。Application Auto Scaling 使用*目標追蹤*演算法，向上或向下調整資料表 (或索引) 的佈建輸送量，以此回應實際的工作負載，讓實際容量使用率保持或接近目標使用率。

DynamoDB 會以一分鐘為週期，輸出耗用的佈建輸送量。當耗用容量連續兩分鐘超過設定的目標使用率時，自動擴展即會觸發。CloudWatch 警示在觸發自動擴展前，可能會有短暫數分鐘的延遲。此延遲可確保 CloudWatch 指標的準確評估。若耗用輸送量峰值間隔超過一分鐘，自動擴展可能不會觸發。同理，當連續 15 個資料點低於目標使用率時，會觸發縮減規模事件。無論哪種情況，自動擴展觸發後，會調用 [UpdateTable](https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_UpdateTable.html) API。接著，系統可能需要數分鐘時間來更新資料表或索引的佈建容量。在此期間，所有超出資料表先前佈建容量的請求都會受到限流。

**重要**  
您無法調整資料點數目以觸發底層警示 (但此數值未來可能會變更)。

 您可將自動擴展目標使用率值設定在 20% 至 90% 之間，做為您的讀寫容量。

**注意**  
除了資料表外，DynamoDB Auto Scaling 功能也支援全域次要索引。每個全域次要索引都有自己的佈建輸送容量，與其基礎資料表的佈建輸送容量無關。當您為全域次要索引建立擴展政策時，Application Auto Scaling 會調整索引的佈建輸送量設定，以確保其實際使用率保持或接近您想要的使用比率。

## DynamoDB Auto Scaling 功能的運作方式
<a name="AutoScaling.HowItWorks"></a>

**注意**  
若要快速開始使用 DynamoDB Auto Scaling 功能，請參閱 [AWS 管理主控台 搭配 DynamoDB Auto Scaling 使用](AutoScaling.Console.md)。

下圖提供 DynamoDB Auto Scaling 功能如何管理資料表輸送容量的高層級概觀。

![\[DynamoDB 自動擴展會依需求調整資料表的輸送容量。\]](http://docs.aws.amazon.com/zh_tw/amazondynamodb/latest/developerguide/images/auto-scaling.png)


下列步驟摘要說明上圖所示的自動擴展程序：

1. 您可以為 DynamoDB 資料表建立 Application Auto Scaling 政策。

1. DynamoDB 會將耗用的容量指標發布至 Amazon CloudWatch。

1. 若資料表的使用容量持續一段特定時間都超過目標使用率 (或低於目標)，Amazon CloudWatch 會觸發警示。您可以在主控台檢視警示，並使用 Amazon Simple Notification Service (Amazon SNS) 接收通知。

1. CloudWatch 警示會調用 Application Auto Scaling 來評估擴展政策。

1. Application Auto Scaling 發出 `UpdateTable` 請求來調整資料表的佈建輸送量。

1. DynamoDB 處理 `UpdateTable` 請求，並動態增加 (或減少) 資料表的佈建輸送容量，以便接近您的目標使用率。

若要了解 DynamoDB Auto Scaling 功能的運作方式，請假設您有一個名為 `ProductCatalog` 的資料表。該資料表不常大量載入資料，因此不會產生太多寫入活動。不過，它會發生大量讀取活動，並會隨著時間變化。透過監控 `ProductCatalog` 的 Amazon CloudWatch 指標，您判斷出資料表需要 1,200 個讀取容量單位 (以避免 DynamoDB 在活動尖峰時限流讀取請求)。您也判斷出當讀取流量在最低點時，`ProductCatalog` 至少需要 150 個讀取容量單位。如需防止限流的詳細資訊，請參閱 [在 Amazon DynamoDB 中針對限流問題進行疑難排解](TroubleshootingThrottling.md)。

在 150 到 1,200 個讀取容量單位範圍內，您決定 `ProductCatalog` 資料表的適當目標使用率為 70%。*目標使用率*是以使用容量單位與佈建容量單位的比率，以百分比表示。Application Auto Scaling 使用其目標追蹤演算法，確保視需要調整 `ProductCatalog` 的佈建讀取容量，讓使用率維持在或接近 70%。

**注意**  
只有在實際工作負載持續幾分鐘保持很高 (或很低) 的狀態時，DynamoDB Auto Scaling 功能才會修改佈建輸送量設定。Application Auto Scaling 目標追蹤演算法會設法長期將目標使用率保持在或接近您選擇的數值。  
資料表的內建高載容量可應付短期遽增的活動。如需詳細資訊，請參閱[高載容量](burst-adaptive-capacity.md#burst-capacity)。

若要為 `ProductCatalog` 資料表啟用 DynamoDB Auto Scaling 功能，您可以建立擴展政策。此政策會指定以下內容：
+ 要管理的資料表或全域次要索引
+ 要管理的容量類型 (讀取容量或寫入容量)
+ 佈建輸送量設定的上限與下限
+ 您的目標使用率

當您建立擴展政策時，Application Auto Scaling 會代您建立一組 Amazon CloudWatch 警示。每組警示皆代表您佈建輸送量設定的上限與下限。當資料表的實際使用率持續一段時間偏離您的目標使用率時，就會觸發這些 CloudWatch 警示。

當其中一個 CloudWatch 警示觸發時，Amazon SNS 會傳送通知給您 (若已啟用)。然後 CloudWatch 警示會調用 Application Auto Scaling，再由其通知 DynamoDB 適當地將 `ProductCatalog` 資料表的佈建容量調高或調低。

在擴展事件期間，每個記錄的組態項目 AWS Config 都會收費。當發生擴展事件時，系統會針對每個讀取與寫入自動擴展事件建立四個 CloudWatch 警示：ProvisionedCapacity 警示 (ProvisionedCapacityLow、ProvisionedCapacityHigh) 以及 ConsumedCapacity 警示 (AlarmHigh、AlarmLow)。這樣總共會產生八個警示。因此， 會為每個擴展事件 AWS Config 記錄八個組態項目。

**注意**  
您也可以設定 DynamoDB 擴展的排程，使其在特定時間執行。[在此](https://docs.aws.amazon.com/autoscaling/application/userguide/get-started-exercise.html)了解基本步驟。

## 使用須知
<a name="AutoScaling.UsageNotes"></a>

開始使用 DynamoDB Auto Scaling 功能之前，您應該注意下列事項：
+ DynamoDB Auto Scaling 功能可根據您的自動擴展政策，視需要經常增加讀取容量或寫入容量。所有 DynamoDB 配額仍然有效，如 [Amazon DynamoDB 中的配額](ServiceQuotas.md) 所述。
+ DynamoDB Auto Scaling 功能不會阻止您手動修改佈建輸送量設定。這些手動調整不會影響與 DynamoDB Auto Scaling 相關的任何現有 CloudWatch 警示。
+ 如果您為具有一或多個全域次要索引的資料表啟用 DynamoDB Auto Scaling，強烈建議您也將自動擴展統一套用至這些索引。這將有助於確保改善資料表的寫入和讀取效能，並有助於避免限流。您可以在 AWS 管理主控台中選取 **Apply same settings to global secondary indexes** (將相同的設定套用至全域次要索引) 來啟用自動擴展的功能。如需詳細資訊，請參閱[在現有資料表上啟用 DynamoDB Auto Scaling 功能](AutoScaling.Console.md#AutoScaling.Console.ExistingTable)。
+ 刪除資料表或全域資料表複本時，任何相關聯的可擴展目標、擴展政策或 CloudWatch 警示都不會跟著自動刪除。
+ 為現有資料表建立 GSI 時，不會為 GSI 啟用 Auto Scaling。建置 GSI 時，您必須手動管理容量。GSI 上的回填完成並達到活動狀態後，Auto Scaling 的操作將恢復正常。

# AWS 管理主控台 搭配 DynamoDB Auto Scaling 使用
<a name="AutoScaling.Console"></a>

當您使用 AWS 管理主控台 建立新的資料表時，預設會為該資料表啟用 Amazon DynamoDB 自動擴展。您也可以使用主控台，啟用現有資料表的自動擴展、修改自動擴展設定或停用自動擴展。

**注意**  
 如需設定向內擴展和向外擴展冷卻時間等更進階的功能，請使用 AWS Command Line Interface (AWS CLI) 來管理 DynamoDB 自動擴展。如需詳細資訊，請參閱[使用 AWS CLI 管理 DynamoDB 自動擴展](AutoScaling.CLI.md)。

**Topics**
+ [開始之前：授予 DynamoDB Auto Scaling 功能的使用者許可](#AutoScaling.Permissions)
+ [建立啟用 Auto Scaling 的新資料表](#AutoScaling.Console.NewTable)
+ [在現有資料表上啟用 DynamoDB Auto Scaling 功能](#AutoScaling.Console.ExistingTable)
+ [在主控台上檢視自動擴展活動](#AutoScaling.Console.ViewingActivities)
+ [修改或停用 DynamoDB Auto Scaling 設定](#AutoScaling.Console.Modifying)

## 開始之前：授予 DynamoDB Auto Scaling 功能的使用者許可
<a name="AutoScaling.Permissions"></a>

在 AWS Identity and Access Management (IAM) 中， AWS 受管政策`DynamoDBFullAccess`提供使用 DynamoDB 主控台所需的許可。不過，如需 DynamoDB Auto Scaling 功能，則使用者需要額外的權限。

**重要**  
 須有 `application-autoscaling:*` 許可才能刪除已啟用自動擴展功能的資料表。 AWS 受管政策`DynamoDBFullAccess`包含這類許可。

若要為使用者設定 DynamoDB 主控台存取和 DynamoDB Auto Scaling，請建立角色，接著將 **AmazonDynamoDBFullAccess** 政策新增至該角色。然後將角色指派給使用者。

## 建立啟用 Auto Scaling 的新資料表
<a name="AutoScaling.Console.NewTable"></a>

**注意**  
DynamoDB Auto Scaling 需要有服務連結角色 (`AWSServiceRoleForApplicationAutoScaling_DynamoDBTable`)，其會代表您執行自動擴展動作。系統會自動建立此角色。如需詳細資訊，請參閱《*Application Auto Scaling 使用者指南*》中的[適用於 Application Auto Scaling 的服務連結角色](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html)。

**在啟用 Auto Scaling 的情況下建立新資料表**

1. 請在 [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/) 開啟 DynamoDB 主控台。

1. 選擇 **Create Table** (建立資料表)。

1. 在**建立資料表**頁面上，輸入**資料表名稱**和主索引鍵詳細資訊。

1. 若選擇**預設設定**，系統會自動在新資料表中啟用自動擴展。

   否則，請選擇**自訂設定**，然後依下列步驟設定資料表的自訂參數：

   1. 在**資料表類別**中，請維持 **DynamoDB Standard** 的預設選項。

   1. 在**讀取/寫入容量設定**中，維持**佈建**為預設選項，然後依下列步驟操作：

      1. 在**讀取容量**中，請確認**自動擴展**已設定為**開啟**。

      1. 在**寫入容量**中，請確定**自動擴展**已設定為**開啟**。

      1. 在**讀取容量**與**寫入容量**中，請為資料表設定所需的擴展策略，並可選擇性地套用至所有全域次要索引。
         + **容量單位下限**：輸入自動擴展範圍的下限。
         + **容量單位上限**：輸入自動擴展範圍的上限。
         + **目標使用率**：輸入資料表的目標使用率百分比。
**注意**  
如果您為新資料表建立全域次要索引，則建立時索引的容量將與基礎資料表的容量相同。建立資料表後，您可以在資料表的設定中變更索引的容量。

1. 選擇 **Create Table** (建立資料表)。系統會根據您指定的自動擴展參數建立資料表。

## 在現有資料表上啟用 DynamoDB Auto Scaling 功能
<a name="AutoScaling.Console.ExistingTable"></a>

**注意**  
DynamoDB Auto Scaling 需要有服務連結角色 (`AWSServiceRoleForApplicationAutoScaling_DynamoDBTable`)，其會代表您執行自動擴展動作。系統會自動建立此角色。如需詳細資訊，請參閱 [Application Auto Scaling 的服務連結角色](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html)。

**啟用現有資料表的 DynamoDB Auto Scaling**

1. 請在 [https://console.aws.amazon.com/dynamodb/](https://console.aws.amazon.com/dynamodb/) 開啟 DynamoDB 主控台。

1. 在主控台左側的導覽窗格中，選擇 **Tables** (資料表)。

1. 選擇要啟用自動擴展的資料表，然後依下列步驟操作：

   1. 前往**其他設定**分頁。

   1. 在 **Read/write capacity** (讀取/寫入容量) 區段中，選擇 **Edit** (編輯)。

   1. 在 **Capacity mode** (容量模式) 區段中，選擇 **Provisioned** (佈建)。

   1. 在 **Table capacity** (資料表容量) 區段，將 **Read capacity** (讀取容量)、**Write capacity** (寫入容量)，或兩者的 **Auto scaling** (自動擴展) 設定為 **On** (開啟)。針對這些項目，請為資料表設定所需的擴展政策，並選擇性地設定資料表的所有全域次要索引。
      + **容量單位下限**：輸入自動擴展範圍的下限。
      + **容量單位上限**：輸入自動擴展範圍的上限。
      + **目標使用率**：輸入資料表的目標使用率百分比。
      + **對所有全域次要索引使用相同的容量讀取/寫入容量設定**-選擇全域次要索引是否應該使用與基礎資料表相同的自動擴展政策。
**注意**  
為獲得最佳效能，我們建議您啟用 **Use the same read/write capacity settings for all global secondary indexes** (針對全部全域次要索引使用相同的讀取/寫入容量設定)。此選項允許 DynamoDB Auto Scaling 功能以統一方式擴展基礎資料表上的所有全域次要索引。這包括現有的全域次要索引，以及您未來為此資料表建立的任何其他索引。  
啟用此選項後，您就無法在個別全域次要索引上設定擴展政策。

1. 當您滿意設定後，請選擇 **Save** (儲存)。

## 在主控台上檢視自動擴展活動
<a name="AutoScaling.Console.ViewingActivities"></a>

當應用程式將讀取和寫入流量推送至資料表時，DynamoDB Auto Scaling 功能會動態修改資料表的輸送量設定。Amazon CloudWatch 會追蹤所有 DynamoDB 資料表和次要索引的佈建和耗用容量、限流事件、延遲和其他指標。

若要在 DynamoDB 主控台中檢視這些指標，請選擇要使用的資料表，然後選擇 **Monitor** (監控) 索引標籤。若要建立資料表指標的可自訂檢視，請選取 **View all in CloudWatch** (在 CloudWatch 檢視全部)。

## 修改或停用 DynamoDB Auto Scaling 設定
<a name="AutoScaling.Console.Modifying"></a>

您可以使用 AWS 管理主控台 來修改 DynamoDB 自動擴展設定。若要這樣做，請前往 **Additional settings** (其他設定) 索引標籤，然後選擇 **Edit** (編輯) 中的 **Read/write capacity** (讀取/寫入容量) 一節。如需這些設定的詳細資訊，請參閱 [在現有資料表上啟用 DynamoDB Auto Scaling 功能](#AutoScaling.Console.ExistingTable)。

# 使用 AWS CLI 管理 DynamoDB 自動擴展
<a name="AutoScaling.CLI"></a>

您可以使用 AWS Command Line Interface (AWS CLI) 管理 Amazon DynamoDB 自動擴展 AWS 管理主控台，而不是使用 。本節中的教學課程會示範如何安裝和設定 AWS CLI 來管理 DynamoDB Auto Scaling 功能。在此教學課程中，您將執行下列操作：
+ 建立名為 `TestTable` 的 DynamoDB 資料表。初始輸送量設定是 5 個讀取容量單位和 5 個寫入容量單位。
+ 為 `TestTable` 建立 Application Auto Scaling 政策。該政策會設法將使用寫入容量與佈建寫入容量之間的目標比率保持在 50%。此指標範圍介於 5 到 10 個寫入容量單位之間。(Application Auto Scaling 無法調整超出此範圍的輸送量。)
+ 運行 Python 程式來將寫入流量推送至 `TestTable`。當目標比率持續超過 50% 時，Application Auto Scaling 會通知 DynamoDB 提高 `TestTable` 的輸送量，以便維持 50% 的目標使用率。
+ 確認 DynamoDB 已成功調整 `TestTable` 的佈建寫入容量。

**注意**  
您也可以設定 DynamoDB 擴展的排程，使其在特定時間執行。[在此](https://docs.aws.amazon.com/autoscaling/application/userguide/get-started-exercise.html)了解基本步驟。

**Topics**
+ [開始之前](#AutoScaling.CLI.BeforeYouBegin)
+ [步驟 1：建立 DynamoDB 資料表](#AutoScaling.CLI.CreateTable)
+ [步驟 2：註冊可擴展的目標](#AutoScaling.CLI.RegisterScalableTarget)
+ [步驟 3：建立擴展政策](#AutoScaling.CLI.CreateScalingPolicy)
+ [步驟 4：將寫入流量導向 TestTable](#AutoScaling.CLI.DriveTraffic)
+ [步驟 5：檢視 Application Auto Scaling 動作](#AutoScaling.CLI.ViewCWAlarms)
+ [(選用) 步驟 6：清除](#AutoScaling.CLI.CleanUp)

## 開始之前
<a name="AutoScaling.CLI.BeforeYouBegin"></a>

開始這些教學課程之前，請完成以下任務。

### 安裝 AWS CLI
<a name="AutoScaling.CLI.BeforeYouBegin.InstallCLI"></a>

若您尚未執行此作業，您必須安裝及設定 AWS CLI。若要執行此作業，請遵循《*AWS Command Line Interface 使用者指南*》中的這些說明：
+ [安裝 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/installing.html)
+ [設定 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)

### 安裝 Python
<a name="AutoScaling.CLI.BeforeYouBegin.InstallPython"></a>

本教學課程的一部分會要求您執行 Python 程式 (請參閱 [步驟 4：將寫入流量導向 TestTable](#AutoScaling.CLI.DriveTraffic))。如果您還沒有安裝 Python 程式，則可以[下載 Python](https://www.python.org/downloads)。

## 步驟 1：建立 DynamoDB 資料表
<a name="AutoScaling.CLI.CreateTable"></a>

在此步驟中，您會使用 AWS CLI 來建立 `TestTable`。主索引鍵包含 `pk` (分割區索引鍵) 和 `sk` (排序索引鍵)。這些屬性的類型皆為 `Number`。初始輸送量設定是 5 個讀取容量單位和 5 個寫入容量單位。

1. 使用下列 AWS CLI 命令來建立資料表。

   ```
   aws dynamodb create-table \
       --table-name TestTable \
       --attribute-definitions \
           AttributeName=pk,AttributeType=N \
           AttributeName=sk,AttributeType=N \
       --key-schema \
           AttributeName=pk,KeyType=HASH \
           AttributeName=sk,KeyType=RANGE \
       --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5
   ```

1. 若要檢查資料表的狀態，請使用以下命令。

   ```
   aws dynamodb describe-table \
       --table-name TestTable \
       --query "Table.[TableName,TableStatus,ProvisionedThroughput]"
   ```

   當資料表狀態為 `ACTIVE` 時，即可供使用。

## 步驟 2：註冊可擴展的目標
<a name="AutoScaling.CLI.RegisterScalableTarget"></a>

接下來，您可以使用 Application Auto Scaling 將資料表寫入容量註冊為可擴展的目標。這可讓 Application Auto Scaling 調整 *TestTable* 的佈建寫入容量，但僅在 5 至 10 個容量單位的範圍內。

**注意**  
DynamoDB Auto Scaling 需要有服務連結角色 (`AWSServiceRoleForApplicationAutoScaling_DynamoDBTable`)，其會代表您執行自動擴展動作。系統會自動建立此角色。如需詳細資訊，請參閱《*Application Auto Scaling 使用者指南*》中的[適用於 Application Auto Scaling 的服務連結角色](https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html)。

1. 輸入下列命令來註冊可擴展的目標。

   ```
   aws application-autoscaling register-scalable-target \
       --service-namespace dynamodb \
       --resource-id "table/TestTable" \
       --scalable-dimension "dynamodb:table:WriteCapacityUnits" \
       --min-capacity 5 \
       --max-capacity 10
   ```

1. 若要確認註冊，請使用下列命令。

   ```
   aws application-autoscaling describe-scalable-targets \
       --service-namespace dynamodb \
       --resource-id "table/TestTable"
   ```
**注意**  
 您也可以針對全域次要索引註冊可擴展的目標。例如，對於全域次要索引 (test-index)，資源 ID 和可擴展的維度引數會適當地更新。  

   ```
   aws application-autoscaling register-scalable-target \
       --service-namespace dynamodb \
       --resource-id "table/TestTable/index/test-index" \
       --scalable-dimension "dynamodb:index:WriteCapacityUnits" \
       --min-capacity 5 \
       --max-capacity 10
   ```

## 步驟 3：建立擴展政策
<a name="AutoScaling.CLI.CreateScalingPolicy"></a>

在此步驟中，您會建立 `TestTable` 的擴展政策。此政策會定義 Application Auto Scaling 可在哪些詳細資訊下調整資料表的佈建輸送量，以及在執行此動作時要採取的動作。您可以將此政策與您在上一個步驟中定義的可擴展目標建立關聯 (`TestTable` 資料表的寫入容量單位)。

該政策包含下列元素：
+ `PredefinedMetricSpecification`：允許 Application Auto Scaling 調整的指標。對於 DynamoDB，下列值是 `PredefinedMetricType` 的有效值：
  + `DynamoDBReadCapacityUtilization`
  + `DynamoDBWriteCapacityUtilization`
+ `ScaleOutCooldown`：提高佈建輸送量的每個 Application Auto Scaling 事件之間的最短時間 (以秒為單位)。此參數可讓 Application Auto Scaling 持續 (但不積極) 增加輸送量，以便回應真實的工作負載。`ScaleOutCooldown` 的預設設定為 0。
+ `ScaleInCooldown`：減少佈建輸送量的每個 Application Auto Scaling 事件之間的最短時間 (以秒為單位)。此參數可讓 Application Auto Scaling 以逐漸且可預測的方式降低輸送量。`ScaleInCooldown` 的預設設定為 0。
+ `TargetValue`：Application Auto Scaling 可確保將耗用容量與佈建容量的比率保持在此值或接近此數值。您能以百分比的形式定義 `TargetValue`。

**注意**  
為了進一步了解 `TargetValue` 如何運作，請假設您資料表的佈建輸送量設定為 200 個寫入容量單位。您決定為此資料表建立擴展政策，並將 `TargetValue` 設為 70 %。  
現在，假設您開始將寫入流量導向該資料表，那實際的寫入輸送量就會是 150 個容量單位。耗用與佈建比率現在為 (150/200)，也就是 75%。此比率超過您的目標，因此 Application Auto Scaling 會將佈建的寫入容量提高至 215，使得比率成為 (150/215) (也就是 69.77 百分比)；盡可能靠近但不超過 `TargetValue`。

對於 `TestTable`，您將 `TargetValue` 設為 50%。Application Auto Scaling 將資料表佈建的輸送量調整在 5–10 個容量單位的範圍內 (請參閱 [步驟 2：註冊可擴展的目標](#AutoScaling.CLI.RegisterScalableTarget))，使耗用與佈建的比率維持在或接近 50%。您可以將 `ScaleOutCooldown` 和 `ScaleInCooldown` 的數值設為 60 秒。

1. 使用下列內容建立名為 `scaling-policy.json` 的檔案。

   ```
   {
       "PredefinedMetricSpecification": {
           "PredefinedMetricType": "DynamoDBWriteCapacityUtilization"
       },
       "ScaleOutCooldown": 60,
       "ScaleInCooldown": 60,
       "TargetValue": 50.0
   }
   ```

1. 使用下列 AWS CLI 命令來建立政策。

   ```
   aws application-autoscaling put-scaling-policy \
       --service-namespace dynamodb \
       --resource-id "table/TestTable" \
       --scalable-dimension "dynamodb:table:WriteCapacityUnits" \
       --policy-name "MyScalingPolicy" \
       --policy-type "TargetTrackingScaling" \
       --target-tracking-scaling-policy-configuration file://scaling-policy.json
   ```

1. 請注意，在輸出中，Application Auto Scaling 已建立兩個 Amazon CloudWatch 警示：擴展目標範圍的上限和下限各一個警示。

1. 使用下列 AWS CLI 命令來檢視擴展政策的詳細資訊。

   ```
   aws application-autoscaling describe-scaling-policies \
       --service-namespace dynamodb \
       --resource-id "table/TestTable" \
       --policy-name "MyScalingPolicy"
   ```

1. 在輸出中，確認政策設定符合 [步驟 2：註冊可擴展的目標](#AutoScaling.CLI.RegisterScalableTarget) 和 [步驟 3：建立擴展政策](#AutoScaling.CLI.CreateScalingPolicy) 中的規格。

## 步驟 4：將寫入流量導向 TestTable
<a name="AutoScaling.CLI.DriveTraffic"></a>

現在，您可以將資料寫入 `TestTable` 來測試擴展政策。為此，您須執行 Python 程式。

1. 使用下列內容建立名為 `bulk-load-test-table.py` 的檔案。

   ```
   import boto3
   dynamodb = boto3.resource('dynamodb')
   
   table = dynamodb.Table("TestTable")
   
   filler = "x" * 100000
   
   i = 0
   while (i < 10):
       j = 0
       while (j < 10):
           print (i, j)
           
           table.put_item(
               Item={
                   'pk':i,
                   'sk':j,
                   'filler':{"S":filler}
               }
           )
           j += 1
       i += 1
   ```

1. 請輸入下列命令來執行程式。

   `python bulk-load-test-table.py`

   `TestTable` 的佈建寫入容量非常低 (5 個寫入容量單位)，因此程式偶爾會因寫入限流而停滯。這是預期的行為。

   讓程式繼續執行，您則繼續下一個步驟。

## 步驟 5：檢視 Application Auto Scaling 動作
<a name="AutoScaling.CLI.ViewCWAlarms"></a>

 在此步驟中，您可以檢視代表您啟動的 Application Auto Scaling 動作。您也可以確認 Application Auto Scaling 已更新 `TestTable` 的佈建寫入容量。

1. 輸入下列命令來檢視 Application Auto Scaling 動作。

   ```
   aws application-autoscaling describe-scaling-activities \
       --service-namespace dynamodb
   ```

   在 Python 程式執行時，偶爾重新執行此命令。(調用擴展政策需要幾分鐘的時間。) 您最終應該會看到下列輸出。

   ```
   ...
   {
       "ScalableDimension": "dynamodb:table:WriteCapacityUnits", 
       "Description": "Setting write capacity units to 10.", 
       "ResourceId": "table/TestTable", 
       "ActivityId": "0cc6fb03-2a7c-4b51-b67f-217224c6b656", 
       "StartTime": 1489088210.175, 
       "ServiceNamespace": "dynamodb", 
       "EndTime": 1489088246.85, 
       "Cause": "monitor alarm AutoScaling-table/TestTable-AlarmHigh-1bb3c8db-1b97-4353-baf1-4def76f4e1b9 in state ALARM triggered policy MyScalingPolicy", 
       "StatusMessage": "Successfully set write capacity units to 10. Change successfully fulfilled by dynamodb.", 
       "StatusCode": "Successful"
   }, 
   ...
   ```

   這表示 Application Auto Scaling 已對 DynamoDB 發出 `UpdateTable` 請求。

1. 輸入下列命令，確認 DynamoDB 已增加資料表的寫入容量。

   ```
   aws dynamodb describe-table \
       --table-name TestTable \
       --query "Table.[TableName,TableStatus,ProvisionedThroughput]"
   ```

   `WriteCapacityUnits` 應該從 `5` 擴展至 `10`。

## (選用) 步驟 6：清除
<a name="AutoScaling.CLI.CleanUp"></a>

在此教學課程中，您已建立數個資源。如果不再需要這些資源，就可以將其刪除。

1. 刪除 `TestTable` 的擴展政策。

   ```
   aws application-autoscaling delete-scaling-policy \
       --service-namespace dynamodb \
       --resource-id "table/TestTable" \
       --scalable-dimension "dynamodb:table:WriteCapacityUnits" \
       --policy-name "MyScalingPolicy"
   ```

1. 取消註冊可擴展的目標。

   ```
   aws application-autoscaling deregister-scalable-target \
       --service-namespace dynamodb \
       --resource-id "table/TestTable" \
       --scalable-dimension "dynamodb:table:WriteCapacityUnits"
   ```

1. 刪除 `TestTable` 資料表。

   ```
   aws dynamodb delete-table --table-name TestTable
   ```

# 使用 AWS SDK 在 Amazon DynamoDB 資料表上設定自動擴展
<a name="AutoScaling.HowTo.SDK"></a>

除了使用 AWS 管理主控台 和 AWS Command Line Interface (AWS CLI)，您還可以撰寫與 Amazon DynamoDB Auto Scaling 互動的應用程式。本節包含可用來測試此功能的兩個 Java 程式：
+ `EnableDynamoDBAutoscaling.java`
+ `DisableDynamoDBAutoscaling.java`

## 啟用資料表的 Application Auto Scaling
<a name="AutoScaling.HowTo.SDK-enable"></a>

以下程式顯示 DynamoDB 資料表 (`TestTable`) 自動擴展政策的設定範例。它會繼續如下：
+ 此程式會將寫入容量單位註冊為 `TestTable` 的可擴展目標。此指標範圍介於 5 到 10 個寫入容量單位之間。
+ 建立可擴展目標之後，程式會建置目標追蹤組態。該政策會設法將使用寫入容量與佈建寫入容量之間的目標比率保持在 50%。
+ 程式接著會根據目標追蹤組態來建立擴展政策。

**注意**  
手動移除資料表或全域資料表複本時，不會自動移除任何相關聯的可擴展目標、擴展政策或 CloudWatch 警示。

------
#### [ Java v2 ]

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.PolicyType;
import software.amazon.awssdk.services.applicationautoscaling.model.PredefinedMetricSpecification;
import software.amazon.awssdk.services.applicationautoscaling.model.PutScalingPolicyRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.RegisterScalableTargetRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalingPolicy;
import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;
import software.amazon.awssdk.services.applicationautoscaling.model.MetricType;
import software.amazon.awssdk.services.applicationautoscaling.model.TargetTrackingScalingPolicyConfiguration;
import java.util.List;

/**
 * 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 EnableDynamoDBAutoscaling {
    public static void main(String[] args) {
        final String usage = """

            Usage:
               <tableId> <roleARN> <policyName>\s

            Where:
               tableId - The table Id value (for example, table/Music).
               roleARN - The ARN of the role that has ApplicationAutoScaling permissions.
               policyName - The name of the policy to create.
               
            """;

        if (args.length != 3) {
            System.out.println(usage);
            System.exit(1);
        }

        System.out.println("This example registers an Amazon DynamoDB table, which is the resource to scale.");
        String tableId = args[0];
        String roleARN = args[1];
        String policyName = args[2];
        ServiceNamespace ns = ServiceNamespace.DYNAMODB;
        ScalableDimension tableWCUs = ScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS;
        ApplicationAutoScalingClient appAutoScalingClient = ApplicationAutoScalingClient.builder()
            .region(Region.US_EAST_1)
            .build();

        registerScalableTarget(appAutoScalingClient, tableId, roleARN, ns, tableWCUs);
        verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs);
        configureScalingPolicy(appAutoScalingClient, tableId, ns, tableWCUs, policyName);
    }

    public static void registerScalableTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, String roleARN, ServiceNamespace ns, ScalableDimension tableWCUs) {
        try {
            RegisterScalableTargetRequest targetRequest = RegisterScalableTargetRequest.builder()
                .serviceNamespace(ns)
                .scalableDimension(tableWCUs)
                .resourceId(tableId)
                .roleARN(roleARN)
                .minCapacity(5)
                .maxCapacity(10)
                .build();

            appAutoScalingClient.registerScalableTarget(targetRequest);
            System.out.println("You have registered " + tableId);

        } catch (ApplicationAutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    // Verify that the target was created.
    public static void verifyTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        DescribeScalableTargetsRequest dscRequest = DescribeScalableTargetsRequest.builder()
            .scalableDimension(tableWCUs)
            .serviceNamespace(ns)
            .resourceIds(tableId)
            .build();

        DescribeScalableTargetsResponse response = appAutoScalingClient.describeScalableTargets(dscRequest);
        System.out.println("DescribeScalableTargets result: ");
        System.out.println(response);
    }

    // Configure a scaling policy.
    public static void configureScalingPolicy(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs, String policyName) {
        // Check if the policy exists before creating a new one.
        DescribeScalingPoliciesResponse describeScalingPoliciesResponse = appAutoScalingClient.describeScalingPolicies(DescribeScalingPoliciesRequest.builder()
            .serviceNamespace(ns)
            .resourceId(tableId)
            .scalableDimension(tableWCUs)
            .build());

        if (!describeScalingPoliciesResponse.scalingPolicies().isEmpty()) {
            // If policies exist, consider updating an existing policy instead of creating a new one.
            System.out.println("Policy already exists. Consider updating it instead.");
            List<ScalingPolicy> polList = describeScalingPoliciesResponse.scalingPolicies();
            for (ScalingPolicy pol : polList) {
                System.out.println("Policy name:" +pol.policyName());
            }
        } else {
            // If no policies exist, proceed with creating a new policy.
            PredefinedMetricSpecification specification = PredefinedMetricSpecification.builder()
                .predefinedMetricType(MetricType.DYNAMO_DB_WRITE_CAPACITY_UTILIZATION)
                .build();

            TargetTrackingScalingPolicyConfiguration policyConfiguration = TargetTrackingScalingPolicyConfiguration.builder()
                .predefinedMetricSpecification(specification)
                .targetValue(50.0)
                .scaleInCooldown(60)
                .scaleOutCooldown(60)
                .build();

            PutScalingPolicyRequest putScalingPolicyRequest = PutScalingPolicyRequest.builder()
                .targetTrackingScalingPolicyConfiguration(policyConfiguration)
                .serviceNamespace(ns)
                .scalableDimension(tableWCUs)
                .resourceId(tableId)
                .policyName(policyName)
                .policyType(PolicyType.TARGET_TRACKING_SCALING)
                .build();

            try {
                appAutoScalingClient.putScalingPolicy(putScalingPolicyRequest);
                System.out.println("You have successfully created a scaling policy for an Application Auto Scaling scalable target");
            } catch (ApplicationAutoScalingException e) {
                System.err.println("Error: " + e.awsErrorDetails().errorMessage());
            }
        }
    }
}
```

------
#### [ Java v1 ]

此程式需要您提供有效 Application Auto Scaling 服務連結角色的 Amazon Resource Name (ARN)。(例如：`arn:aws:iam::122517410325:role/AWSServiceRoleForApplicationAutoScaling_DynamoDBTable`。) 在下列程式中，將 `SERVICE_ROLE_ARN_GOES_HERE` 取代為實際 ARN。

```
package com.amazonaws.codesamples.autoscaling;

import com.amazonaws.services.applicationautoscaling.AWSApplicationAutoScalingClient;
import com.amazonaws.services.applicationautoscaling.AWSApplicationAutoScalingClientBuilder;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalableTargetsRequest;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalableTargetsResult;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalingPoliciesResult;
import com.amazonaws.services.applicationautoscaling.model.MetricType;
import com.amazonaws.services.applicationautoscaling.model.PolicyType;
import com.amazonaws.services.applicationautoscaling.model.PredefinedMetricSpecification;
import com.amazonaws.services.applicationautoscaling.model.PutScalingPolicyRequest;
import com.amazonaws.services.applicationautoscaling.model.RegisterScalableTargetRequest;
import com.amazonaws.services.applicationautoscaling.model.ScalableDimension;
import com.amazonaws.services.applicationautoscaling.model.ServiceNamespace;
import com.amazonaws.services.applicationautoscaling.model.TargetTrackingScalingPolicyConfiguration;

public class EnableDynamoDBAutoscaling {

	static AWSApplicationAutoScalingClient aaClient = (AWSApplicationAutoScalingClient) AWSApplicationAutoScalingClientBuilder
			.standard().build();

	public static void main(String args[]) {

		ServiceNamespace ns = ServiceNamespace.Dynamodb;
		ScalableDimension tableWCUs = ScalableDimension.DynamodbTableWriteCapacityUnits;
		String resourceID = "table/TestTable";

		// Define the scalable target
		RegisterScalableTargetRequest rstRequest = new RegisterScalableTargetRequest()
				.withServiceNamespace(ns)
				.withResourceId(resourceID)
				.withScalableDimension(tableWCUs)
				.withMinCapacity(5)
				.withMaxCapacity(10)
				.withRoleARN("SERVICE_ROLE_ARN_GOES_HERE");

		try {
			aaClient.registerScalableTarget(rstRequest);
		} catch (Exception e) {
			System.err.println("Unable to register scalable target: ");
			System.err.println(e.getMessage());
		}

		// Verify that the target was created
		DescribeScalableTargetsRequest dscRequest = new DescribeScalableTargetsRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceIds(resourceID);
		try {
			DescribeScalableTargetsResult dsaResult = aaClient.describeScalableTargets(dscRequest);
			System.out.println("DescribeScalableTargets result: ");
			System.out.println(dsaResult);
			System.out.println();
		} catch (Exception e) {
			System.err.println("Unable to describe scalable target: ");
			System.err.println(e.getMessage());
		}

		System.out.println();

		// Configure a scaling policy
		TargetTrackingScalingPolicyConfiguration targetTrackingScalingPolicyConfiguration = new TargetTrackingScalingPolicyConfiguration()
				.withPredefinedMetricSpecification(
						new PredefinedMetricSpecification()
								.withPredefinedMetricType(MetricType.DynamoDBWriteCapacityUtilization))
				.withTargetValue(50.0)
				.withScaleInCooldown(60)
				.withScaleOutCooldown(60);

		// Create the scaling policy, based on your configuration
		PutScalingPolicyRequest pspRequest = new PutScalingPolicyRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceId(resourceID)
				.withPolicyName("MyScalingPolicy")
				.withPolicyType(PolicyType.TargetTrackingScaling)
				.withTargetTrackingScalingPolicyConfiguration(targetTrackingScalingPolicyConfiguration);

		try {
			aaClient.putScalingPolicy(pspRequest);
		} catch (Exception e) {
			System.err.println("Unable to put scaling policy: ");
			System.err.println(e.getMessage());
		}

		// Verify that the scaling policy was created
		DescribeScalingPoliciesRequest dspRequest = new DescribeScalingPoliciesRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceId(resourceID);

		try {
			DescribeScalingPoliciesResult dspResult = aaClient.describeScalingPolicies(dspRequest);
			System.out.println("DescribeScalingPolicies result: ");
			System.out.println(dspResult);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Unable to describe scaling policy: ");
			System.err.println(e.getMessage());
		}

	}

}
```

------

## 停用資料表的 Application Auto Scaling
<a name="AutoScaling.HowTo.SDK-disable"></a>

下列程式會反轉先前的程序。它會移除自動擴展政策，然後取消註冊可擴展目標。

------
#### [ Java v2 ]

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.applicationautoscaling.ApplicationAutoScalingClient;
import software.amazon.awssdk.services.applicationautoscaling.model.ApplicationAutoScalingException;
import software.amazon.awssdk.services.applicationautoscaling.model.DeleteScalingPolicyRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DeregisterScalableTargetRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalableTargetsResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;
import software.amazon.awssdk.services.applicationautoscaling.model.DescribeScalingPoliciesResponse;
import software.amazon.awssdk.services.applicationautoscaling.model.ScalableDimension;
import software.amazon.awssdk.services.applicationautoscaling.model.ServiceNamespace;

/**
 * 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 DisableDynamoDBAutoscaling {
    public static void main(String[] args) {
        final String usage = """

            Usage:
               <tableId> <policyName>\s

            Where:
               tableId - The table Id value (for example, table/Music).\s
               policyName - The name of the policy (for example, $Music5-scaling-policy). 
        
            """;
        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        ApplicationAutoScalingClient appAutoScalingClient = ApplicationAutoScalingClient.builder()
            .region(Region.US_EAST_1)
            .build();

        ServiceNamespace ns = ServiceNamespace.DYNAMODB;
        ScalableDimension tableWCUs = ScalableDimension.DYNAMODB_TABLE_WRITE_CAPACITY_UNITS;
        String tableId = args[0];
        String policyName = args[1];

        deletePolicy(appAutoScalingClient, policyName, tableWCUs, ns, tableId);
        verifyScalingPolicies(appAutoScalingClient, tableId, ns, tableWCUs);
        deregisterScalableTarget(appAutoScalingClient, tableId, ns, tableWCUs);
        verifyTarget(appAutoScalingClient, tableId, ns, tableWCUs);
    }

    public static void deletePolicy(ApplicationAutoScalingClient appAutoScalingClient, String policyName, ScalableDimension tableWCUs, ServiceNamespace ns, String tableId) {
        try {
            DeleteScalingPolicyRequest delSPRequest = DeleteScalingPolicyRequest.builder()
                .policyName(policyName)
                .scalableDimension(tableWCUs)
                .serviceNamespace(ns)
                .resourceId(tableId)
                .build();

            appAutoScalingClient.deleteScalingPolicy(delSPRequest);
            System.out.println(policyName +" was deleted successfully.");

        } catch (ApplicationAutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    // Verify that the scaling policy was deleted
    public static void verifyScalingPolicies(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        DescribeScalingPoliciesRequest dscRequest = DescribeScalingPoliciesRequest.builder()
            .scalableDimension(tableWCUs)
            .serviceNamespace(ns)
            .resourceId(tableId)
            .build();

        DescribeScalingPoliciesResponse response = appAutoScalingClient.describeScalingPolicies(dscRequest);
        System.out.println("DescribeScalableTargets result: ");
        System.out.println(response);
    }

    public static void deregisterScalableTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        try {
            DeregisterScalableTargetRequest targetRequest = DeregisterScalableTargetRequest.builder()
                .scalableDimension(tableWCUs)
                .serviceNamespace(ns)
                .resourceId(tableId)
                .build();

            appAutoScalingClient.deregisterScalableTarget(targetRequest);
            System.out.println("The scalable target was deregistered.");

        } catch (ApplicationAutoScalingException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
        }
    }

    public static void verifyTarget(ApplicationAutoScalingClient appAutoScalingClient, String tableId, ServiceNamespace ns, ScalableDimension tableWCUs) {
        DescribeScalableTargetsRequest dscRequest = DescribeScalableTargetsRequest.builder()
            .scalableDimension(tableWCUs)
            .serviceNamespace(ns)
            .resourceIds(tableId)
            .build();

        DescribeScalableTargetsResponse response = appAutoScalingClient.describeScalableTargets(dscRequest);
        System.out.println("DescribeScalableTargets result: ");
        System.out.println(response);
    }
}
```

------
#### [ Java v1 ]

```
package com.amazonaws.codesamples.autoscaling;

import com.amazonaws.services.applicationautoscaling.AWSApplicationAutoScalingClient;
import com.amazonaws.services.applicationautoscaling.model.DeleteScalingPolicyRequest;
import com.amazonaws.services.applicationautoscaling.model.DeregisterScalableTargetRequest;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalableTargetsRequest;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalableTargetsResult;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalingPoliciesRequest;
import com.amazonaws.services.applicationautoscaling.model.DescribeScalingPoliciesResult;
import com.amazonaws.services.applicationautoscaling.model.ScalableDimension;
import com.amazonaws.services.applicationautoscaling.model.ServiceNamespace;

public class DisableDynamoDBAutoscaling {

	static AWSApplicationAutoScalingClient aaClient = new AWSApplicationAutoScalingClient();

	public static void main(String args[]) {

		ServiceNamespace ns = ServiceNamespace.Dynamodb;
		ScalableDimension tableWCUs = ScalableDimension.DynamodbTableWriteCapacityUnits;
		String resourceID = "table/TestTable";

		// Delete the scaling policy
		DeleteScalingPolicyRequest delSPRequest = new DeleteScalingPolicyRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceId(resourceID)
				.withPolicyName("MyScalingPolicy");

		try {
			aaClient.deleteScalingPolicy(delSPRequest);
		} catch (Exception e) {
			System.err.println("Unable to delete scaling policy: ");
			System.err.println(e.getMessage());
		}

		// Verify that the scaling policy was deleted
		DescribeScalingPoliciesRequest descSPRequest = new DescribeScalingPoliciesRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceId(resourceID);

		try {
			DescribeScalingPoliciesResult dspResult = aaClient.describeScalingPolicies(descSPRequest);
			System.out.println("DescribeScalingPolicies result: ");
			System.out.println(dspResult);
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Unable to describe scaling policy: ");
			System.err.println(e.getMessage());
		}

		System.out.println();

		// Remove the scalable target
		DeregisterScalableTargetRequest delSTRequest = new DeregisterScalableTargetRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceId(resourceID);

		try {
			aaClient.deregisterScalableTarget(delSTRequest);
		} catch (Exception e) {
			System.err.println("Unable to deregister scalable target: ");
			System.err.println(e.getMessage());
		}

		// Verify that the scalable target was removed
		DescribeScalableTargetsRequest dscRequest = new DescribeScalableTargetsRequest()
				.withServiceNamespace(ns)
				.withScalableDimension(tableWCUs)
				.withResourceIds(resourceID);

		try {
			DescribeScalableTargetsResult dsaResult = aaClient.describeScalableTargets(dscRequest);
			System.out.println("DescribeScalableTargets result: ");
			System.out.println(dsaResult);
			System.out.println();
		} catch (Exception e) {
			System.err.println("Unable to describe scalable target: ");
			System.err.println(e.getMessage());
		}

	}

}
```

------