

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

# AWS 服務 使用適用於 C\$1\$1 的 AWS SDK 呼叫 的引導範例
<a name="programming-services"></a>

如果您是初次使用 AWS 或 AWS 程式碼範例，建議您從 開始[程式碼範例入門](getting-started-code-examples.md)。

本指南的 [程式碼範例](cpp_code_examples.md)章節或 GitHub 上的[AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code) 適用於 C\$1\$1 的 AWS SDK 中提供示範如何使用 AWS 服務的原始程式碼。

本節會選取數個 AWS 服務，並引導您使用這些服務的範例。下列引導式範例是 Github 上可用項目的子集。


**包含其他說明的服務範例 （如需完整清單，請參閱[AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code))**  

| 服務 | 服務提供給程式的內容摘要 | 
| --- | --- | 
| [Amazon CloudWatch](examples-cloudwatch.md) | 收集和監控您正在使用 AWS 之資源的指標 | 
| [Amazon DynamoDB](examples-dynamodb.md) | NoSQL 資料庫服務 | 
| [Amazon Elastic Compute Cloud (Amazon EC2)](examples-ec2.md) | 安全、可調整大小的運算容量 | 
| [Amazon Simple Storage Service (Amazon S3)](examples-s3.md) | 資料儲存和擷取 （物件至儲存貯體） | 
| [Amazon Simple Queue Service (Amazon SQS)](examples-sqs.md) | 在軟體元件之間傳送、存放和接收訊息的訊息佇列服務 | 

還有一些範例示範如何使用[非同步方法](async-methods.md)。

若要向 AWS 文件團隊提議新的程式碼範例，請參閱 GitHub [上的貢獻準則](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/CONTRIBUTING.md)以建立新的請求。團隊偏好建立程式碼範例，以顯示廣泛的案例，而不是個別的 API 呼叫。

**在 Windows 上使用程式碼範例**

如果您要使用 SDK 1.9 版在 Windows 上建置範例，請參閱 [針對適用於 C\$1\$1 組建問題的 AWS SDK 進行故障診斷](troubleshooting-cmake.md)。

# 使用 的 Amazon CloudWatch 範例 適用於 C\$1\$1 的 AWS SDK
<a name="examples-cloudwatch"></a>

Amazon CloudWatch (CloudWatch) 是一種監控服務，適用於 AWS 雲端資源和您執行的應用程式 AWS。您可以使用下列範例，使用 編寫 [CloudWatch](https://aws.amazon.com/cloudwatch) 的程式 適用於 C\$1\$1 的 AWS SDK。

Amazon CloudWatch AWS 會即時監控您的 AWS 資源和您在 上執行的應用程式。您可以使用 CloudWatch 收集和追蹤指標，這些是您可以為您的資源和應用程式測量的變數。CloudWatch 警示會根據您定義的規則，傳送通知或自動變更您要監控的資源。

如需有關 CloudWatch 的詳細資訊，請參閱《[Amazon CloudWatch 使用者指南](https://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/)》。

**注意**  
本指南僅提供示範特定技術所需的程式碼，但[完整的範例程式碼可在 GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。在 GitHub 上，您可以下載單一來源檔案，也可以在本機複製儲存庫，以取得、建置和執行所有範例。

**Topics**
+ [從 CloudWatch 取得指標](examples-cloudwatch-get-metrics.md)
+ [發佈自訂指標資料](examples-cloudwatch-publish-custom-metrics.md)
+ [使用 CloudWatch 警示](examples-cloudwatch-create-alarms.md)
+ [在 CloudWatch 中使用警示動作](examples-cloudwatch-use-alarm-actions.md)
+ [將事件傳送至 CloudWatch](examples-cloudwatch-send-events.md)

# 從 CloudWatch 取得指標
<a name="examples-cloudwatch-get-metrics"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 列出指標
<a name="listing-metrics"></a>

若要列出 CloudWatch 指標，請建立 [ListMetricsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_list_metrics_request.html) 並呼叫 CloudWatchClient 的 `ListMetrics`函數。您可以使用 `ListMetricsRequest` 來根據命名空間、指標名稱或維度，篩選傳回的指標。

**注意**  
您可以在 Amazon CloudWatch 使用者指南的 Amazon CloudWatch 指標和維度參考中找到 AWS 服務發佈的指標和維度清單。 [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CW_Support_For_AWS.html) 

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/ListMetricsRequest.h>
#include <aws/monitoring/model/ListMetricsResult.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::ListMetricsRequest request;

        if (argc > 1)
        {
            request.SetMetricName(argv[1]);
        }

        if (argc > 2)
        {
            request.SetNamespace(argv[2]);
        }

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = cw.ListMetrics(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to list CloudWatch metrics:" <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left << std::setw(48) << "MetricName" <<
                    std::setw(32) << "Namespace" << "DimensionNameValuePairs" <<
                    std::endl;
                header = true;
            }

            const auto &metrics = outcome.GetResult().GetMetrics();
            for (const auto &metric : metrics)
            {
                std::cout << std::left << std::setw(48) <<
                    metric.GetMetricName() << std::setw(32) <<
                    metric.GetNamespace();
                const auto &dimensions = metric.GetDimensions();
                for (auto iter = dimensions.cbegin();
                    iter != dimensions.cend(); ++iter)
                {
                    const auto &dimkv = *iter;
                    std::cout << dimkv.GetName() << " = " << dimkv.GetValue();
                    if (iter + 1 != dimensions.cend())
                    {
                        std::cout << ", ";
                    }
                }
                std::cout << std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```

指標會透過呼叫其`GetMetrics`函數，在 [ListMetricsResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_list_metrics_result.html) 中傳回。結果可能會*分頁*。若要擷取下一批結果，`SetNextToken`請使用`ListMetricsResult`物件`GetNextToken`函數的傳回值呼叫原始請求物件，並將修改後的請求物件傳回給另一個 呼叫`ListMetrics`。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/list_metrics.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  Amazon CloudWatch API 參考中的 [ListMetrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/ListMetrics.html)。

# 發佈自訂指標資料
<a name="examples-cloudwatch-publish-custom-metrics"></a>

許多 AWS 服務會在命名空間中發佈[自己的指標](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html)`AWS/`。您也可以使用自己的命名空間發佈自訂指標資料 （只要不是以 開頭`AWS/`)。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 發佈自訂指標資料
<a name="publish-custom-metric-data"></a>

若要發佈您自己的指標資料，請使用 [PutMetricDataRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_put_metric_data_request.html) 呼叫 CloudWatchClient 的 `PutMetricData`函數。`PutMetricDataRequest` 必須在 [MetricDatum](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_metric_datum.html) 物件中包含用於資料的自訂命名空間，以及資料點本身的相關資訊。

**注意**  
您無法指定開頭為 的命名空間`AWS/`。開頭為 的命名空間`AWS/`會保留供 Amazon Web Services 產品使用。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/PutMetricDataRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;

        Aws::CloudWatch::Model::Dimension dimension;
        dimension.SetName("UNIQUE_PAGES");
        dimension.SetValue("URLS");

        Aws::CloudWatch::Model::MetricDatum datum;
        datum.SetMetricName("PAGES_VISITED");
        datum.SetUnit(Aws::CloudWatch::Model::StandardUnit::None);
        datum.SetValue(data_point);
        datum.AddDimensions(dimension);

        Aws::CloudWatch::Model::PutMetricDataRequest request;
        request.SetNamespace("SITE/TRAFFIC");
        request.AddMetricData(datum);

        auto outcome = cw.PutMetricData(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to put sample metric data:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully put sample metric data" << std::endl;
        }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/put_metric_data.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《[Amazon CloudWatch 使用者指南》中的使用 Amazon CloudWatch 指標](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)。 Amazon CloudWatch 
+  《Amazon CloudWatch 使用者指南[AWS 》中的命名空間](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html)。
+  Amazon CloudWatch API 參考中的 [PutMetricData](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricData.html)。

# 使用 CloudWatch 警示
<a name="examples-cloudwatch-create-alarms"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立警示
<a name="create-an-alarm"></a>

若要根據 CloudWatch 指標建立警示，請呼叫 CloudWatchClient 的 `PutMetricAlarm`函數，並將 [PutMetricAlarmRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_put_metric_alarm_request.html) 填入警示條件。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/PutMetricAlarmRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::PutMetricAlarmRequest request;
        request.SetAlarmName(alarm_name);
        request.SetComparisonOperator(
            Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
        request.SetEvaluationPeriods(1);
        request.SetMetricName("CPUUtilization");
        request.SetNamespace("AWS/EC2");
        request.SetPeriod(60);
        request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
        request.SetThreshold(70.0);
        request.SetActionsEnabled(false);
        request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
        request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);

        Aws::CloudWatch::Model::Dimension dimension;
        dimension.SetName("InstanceId");
        dimension.SetValue(instanceId);

        request.AddDimensions(dimension);

        auto outcome = cw.PutMetricAlarm(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch alarm:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch alarm " << alarm_name
                << std::endl;
        }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/put_metric_alarm.cpp)。

## 列出警示
<a name="list-alarms"></a>

若要列出您已建立的 CloudWatch 警示，請使用 [DescribeAlarmsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_describe_alarms_request.html) 呼叫 CloudWatchClient 的 `DescribeAlarms`函數，以用於設定結果的選項。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DescribeAlarmsRequest.h>
#include <aws/monitoring/model/DescribeAlarmsResult.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::DescribeAlarmsRequest request;
        request.SetMaxRecords(1);

        bool done = false;
        bool header = false;
        while (!done)
        {
            auto outcome = cw.DescribeAlarms(request);
            if (!outcome.IsSuccess())
            {
                std::cout << "Failed to describe CloudWatch alarms:" <<
                    outcome.GetError().GetMessage() << std::endl;
                break;
            }

            if (!header)
            {
                std::cout << std::left <<
                    std::setw(32) << "Name" <<
                    std::setw(64) << "Arn" <<
                    std::setw(64) << "Description" <<
                    std::setw(20) << "LastUpdated" <<
                    std::endl;
                header = true;
            }

            const auto &alarms = outcome.GetResult().GetMetricAlarms();
            for (const auto &alarm : alarms)
            {
                std::cout << std::left <<
                    std::setw(32) << alarm.GetAlarmName() <<
                    std::setw(64) << alarm.GetAlarmArn() <<
                    std::setw(64) << alarm.GetAlarmDescription() <<
                    std::setw(20) <<
                    alarm.GetAlarmConfigurationUpdatedTimestamp().ToGmtString(
                        SIMPLE_DATE_FORMAT_STR) <<
                    std::endl;
            }

            const auto &next_token = outcome.GetResult().GetNextToken();
            request.SetNextToken(next_token);
            done = next_token.empty();
        }
```

您可以在 傳回的 [DescribeAlarmsResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_describe_alarms_result.html) `getMetricAlarms`上呼叫 ，以取得警示清單`DescribeAlarms`。

結果可能會*分頁*。若要擷取下一批結果，`SetNextToken`請使用`DescribeAlarmsResult`物件`GetNextToken`函數的傳回值呼叫原始請求物件，並將修改後的請求物件傳回給另一個 呼叫`DescribeAlarms`。

**注意**  
您也可以使用 CloudWatchClient 的 `DescribeAlarmsForMetric`函數來擷取特定指標的警示。其用法類似於 `DescribeAlarms`。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/describe_alarms.cpp)。

## 刪除警示
<a name="delete-alarms"></a>

若要刪除 CloudWatch 警示，請使用 [DeleteAlarmsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_delete_alarms_request.html) 呼叫 CloudWatchClient 的`DeleteAlarms`函數，其中包含您想要刪除的一或多個警示名稱。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DeleteAlarmsRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;
        Aws::CloudWatch::Model::DeleteAlarmsRequest request;
        request.AddAlarmNames(alarm_name);

        auto outcome = cw.DeleteAlarms(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to delete CloudWatch alarm:" <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully deleted CloudWatch alarm " << alarm_name
                << std::endl;
        }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/delete_alarm.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《[Amazon CloudWatch 使用者指南》中的建立 Amazon CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html) Amazon CloudWatch 
+  Amazon CloudWatch API 參考中的 [PutMetricAlarm](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricAlarm.html) 
+  Amazon CloudWatch API 參考中的 [DescribeAlarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/DescribeAlarms.html) 
+  Amazon CloudWatch API 參考中的 [DeleteAlarms](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/DeleteAlarms.html) 

# 在 CloudWatch 中使用警示動作
<a name="examples-cloudwatch-use-alarm-actions"></a>

您可以使用 CloudWatch 警示動作建立警示，以執行自動停止、終止、重新啟動或復原 Amazon EC2 執行個體等動作。

警示動作可以新增至警示，方法是在[建立警示](examples-cloudwatch-create-alarms.md)時使用 [PutMetricAlarmRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_put_metric_alarm_request.html) 的 `SetAlarmActions`函數。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 啟用警示動作
<a name="enable-alarm-actions"></a>

若要啟用 CloudWatch 警示的警示動作，請使用 [EnableAlarmActionsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_enable_alarm_actions_request.html) 呼叫 CloudWatchClient 的 `EnableAlarmActions`，其中包含您想要啟用其動作的一或多個警示名稱。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/EnableAlarmActionsRequest.h>
#include <aws/monitoring/model/PutMetricAlarmRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::CloudWatch::CloudWatchClient cw;
    Aws::CloudWatch::Model::PutMetricAlarmRequest request;
    request.SetAlarmName(alarm_name);
    request.SetComparisonOperator(
        Aws::CloudWatch::Model::ComparisonOperator::GreaterThanThreshold);
    request.SetEvaluationPeriods(1);
    request.SetMetricName("CPUUtilization");
    request.SetNamespace("AWS/EC2");
    request.SetPeriod(60);
    request.SetStatistic(Aws::CloudWatch::Model::Statistic::Average);
    request.SetThreshold(70.0);
    request.SetActionsEnabled(false);
    request.SetAlarmDescription("Alarm when server CPU exceeds 70%");
    request.SetUnit(Aws::CloudWatch::Model::StandardUnit::Seconds);
    request.AddAlarmActions(actionArn);

    Aws::CloudWatch::Model::Dimension dimension;
    dimension.SetName("InstanceId");
    dimension.SetValue(instanceId);
    request.AddDimensions(dimension);

    auto outcome = cw.PutMetricAlarm(request);
    if (!outcome.IsSuccess())
    {
        std::cout << "Failed to create CloudWatch alarm:" <<
            outcome.GetError().GetMessage() << std::endl;
        return;
    }

    Aws::CloudWatch::Model::EnableAlarmActionsRequest enable_request;
    enable_request.AddAlarmNames(alarm_name);

    auto enable_outcome = cw.EnableAlarmActions(enable_request);
    if (!enable_outcome.IsSuccess())
    {
        std::cout << "Failed to enable alarm actions:" <<
            enable_outcome.GetError().GetMessage() << std::endl;
        return;
    }

    std::cout << "Successfully created alarm " << alarm_name <<
        " and enabled actions on it." << std::endl;
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/enable_alarm_actions.cpp)。

## 停用警示動作
<a name="disable-alarm-actions"></a>

若要停用 CloudWatch 警示的警示動作，請使用 [DisableAlarmActionsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-monitoring/html/class_aws_1_1_cloud_watch_1_1_model_1_1_disable_alarm_actions_request.html) 呼叫 CloudWatchClient 的 `DisableAlarmActions`，其中包含您要停用其動作的一或多個警示名稱。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/monitoring/CloudWatchClient.h>
#include <aws/monitoring/model/DisableAlarmActionsRequest.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatch::CloudWatchClient cw;

        Aws::CloudWatch::Model::DisableAlarmActionsRequest disableAlarmActionsRequest;
        disableAlarmActionsRequest.AddAlarmNames(alarm_name);

        auto disableAlarmActionsOutcome = cw.DisableAlarmActions(disableAlarmActionsRequest);
        if (!disableAlarmActionsOutcome.IsSuccess())
        {
            std::cout << "Failed to disable actions for alarm " << alarm_name <<
                ": " << disableAlarmActionsOutcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully disabled actions for alarm " <<
                alarm_name << std::endl;
        }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/disable_alarm_actions.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《Amazon CloudWatch 使用者指南》中的[建立警示以停止、終止、重新啟動或復原執行個體](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/UsingAlarmActions.html) 
+  Amazon CloudWatch API 參考中的 [PutMetricAlarm](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricAlarm.html) 
+  Amazon CloudWatch API 參考中的 [EnableAlarmActions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/EnableAlarmActions.html) 
+  Amazon CloudWatch API 參考中的 [DisableAlarmActions](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/DisableAlarmActions.html) 

# 將事件傳送至 CloudWatch
<a name="examples-cloudwatch-send-events"></a>

CloudWatch Events 提供近乎即時的系統事件串流，描述 Amazon EC2 執行個體、Lambda 函數、Kinesis 串流、Amazon ECS 任務、Step Functions 狀態機器、Amazon SNS 主題、Amazon SQS 佇列或內建目標 AWS 的資源變更。您可以使用簡單的規則，來比對事件，並將這些事件轉傳到一或多個目標函數或串流。

**注意**  
這些程式碼片段假設您了解 [入門 適用於 C\$1\$1 的 AWS SDK](getting-started.md)中的資料，並使用 提供 AWS 登入資料中的資訊來設定預設登入資料。 [AWS](credentials.md)

## 新增事件
<a name="add-events"></a>

若要新增自訂 CloudWatch 事件，請使用 [PutEventsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_events_request.html) 物件呼叫 CloudWatchEventsClient `PutEvents`的函數，該物件包含一或多個 [PutEventsRequestEntry](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_events_request_entry.html) 物件，提供每個事件的詳細資訊。您可以指定項目的多個參數，例如事件的來源和類型、與事件相關聯的資源等等。

**注意**  
對 `putEvents` 的每個呼叫最多可以指定 10 個事件。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutEventsRequest.h>
#include <aws/events/model/PutEventsResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;

        Aws::CloudWatchEvents::Model::PutEventsRequestEntry event_entry;
        event_entry.SetDetail(MakeDetails(event_key, event_value));
        event_entry.SetDetailType("sampleSubmitted");
        event_entry.AddResources(resource_arn);
        event_entry.SetSource("aws-sdk-cpp-cloudwatch-example");

        Aws::CloudWatchEvents::Model::PutEventsRequest request;
        request.AddEntries(event_entry);

        auto outcome = cwe.PutEvents(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to post CloudWatch event: " <<
                outcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout << "Successfully posted CloudWatch event" << std::endl;
        }
```

## 新增規則
<a name="add-rules"></a>

若要建立或更新規則，請使用 [PutRuleRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_rule_request.html) 呼叫 CloudWatchEventsClient `PutRule`的函數，其中包含規則名稱和選用參數，例如[事件模式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html)、要與規則建立關聯的 IAM 角色，以及描述規則執行頻率的[排程表達](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html)式。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutRuleRequest.h>
#include <aws/events/model/PutRuleResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;
        Aws::CloudWatchEvents::Model::PutRuleRequest request;
        request.SetName(rule_name);
        request.SetRoleArn(role_arn);
        request.SetScheduleExpression("rate(5 minutes)");
        request.SetState(Aws::CloudWatchEvents::Model::RuleState::ENABLED);

        auto outcome = cwe.PutRule(request);
        if (!outcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch events rule " <<
                rule_name << ": " << outcome.GetError().GetMessage() <<
                std::endl;
        }
        else
        {
            std::cout << "Successfully created CloudWatch events rule " <<
                rule_name << " with resulting Arn " <<
                outcome.GetResult().GetRuleArn() << std::endl;
        }
```

## 新增目標
<a name="add-targets"></a>

目標是觸發規則時叫用的資源。範例目標包括 Amazon EC2 執行個體、Lambda 函數、Kinesis 串流、Amazon ECS 任務、Step Functions 狀態機器和內建目標。

若要將目標新增至規則，請使用 [PutTargetsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-eventbridge/html/class_aws_1_1_event_bridge_1_1_model_1_1_put_targets_request.html) 呼叫 CloudWatchEventsClient 的`PutTargets`函數，其中包含要更新的規則和要新增至規則的目標清單。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/events/EventBridgeClient.h>
#include <aws/events/model/PutTargetsRequest.h>
#include <aws/events/model/PutTargetsResult.h>
#include <aws/core/utils/Outcome.h>
#include <iostream>
```

 **Code** 

```
        Aws::CloudWatchEvents::EventBridgeClient cwe;

        Aws::CloudWatchEvents::Model::Target target;
        target.SetArn(lambda_arn);
        target.SetId(target_id);

        Aws::CloudWatchEvents::Model::PutTargetsRequest request;
        request.SetRule(rule_name);
        request.AddTargets(target);

        auto putTargetsOutcome = cwe.PutTargets(request);
        if (!putTargetsOutcome.IsSuccess())
        {
            std::cout << "Failed to create CloudWatch events target for rule "
                << rule_name << ": " <<
                putTargetsOutcome.GetError().GetMessage() << std::endl;
        }
        else
        {
            std::cout <<
                "Successfully created CloudWatch events target for rule "
                << rule_name << std::endl;
        }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/eventbridge/put_targets.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《Amazon CloudWatch Events 使用者指南》中的[使用 PutEvents 新增](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html)事件
+  《Amazon CloudWatch Events 使用者指南》中的[規則排程表達式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html) 
+  《Amazon[ CloudWatch Events 使用者指南》中的 CloudWatch Events 的事件類型](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html) Amazon CloudWatch 
+  《Amazon CloudWatch Events 使用者指南》中的[事件和事件模式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html) 
+  Amazon CloudWatch Events API 參考中的 [PutEvents](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutEvents.html) 
+  Amazon CloudWatch Events API 參考中的 [PutTargets](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutTargets.html) 
+  Amazon CloudWatch Events API 參考中的 [PutRule](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutRule.html) 

# 使用 的 Amazon DynamoDB 範例 適用於 C\$1\$1 的 AWS SDK
<a name="examples-dynamodb"></a>

Amazon DynamoDB 是一項完全受管的 NoSQL 資料庫服務，可提供快速且可預期的效能及無縫的可擴展性。下列範例示範如何使用 編寫 [Amazon DynamoDB](https://aws.amazon.com/dynamodb) 的程式 適用於 C\$1\$1 的 AWS SDK。

**注意**  
本指南僅提供示範特定技術所需的程式碼，但[完整的範例程式碼可在 GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。在 GitHub 上，您可以下載單一來源檔案，也可以在本機複製儲存庫，以取得、建置和執行所有範例。

**Topics**
+ [在 DynamoDB 中使用資料表](examples-dynamodb-tables.md)
+ [在 DynamoDB 中使用項目](examples-dynamodb-items.md)

# 在 DynamoDB 中使用資料表
<a name="examples-dynamodb-tables"></a>

資料表是 DynamoDB 資料庫中所有項目的容器。您必須先建立資料表，才能從 DynamoDB 新增或移除資料。

對於每個資料表，您必須定義：
+ 您的 AWS 帳戶 和 的唯一資料表*名稱* AWS 區域。
+ 每個值都必須是唯一*的主索引鍵*。資料表中的兩個項目不能具有相同的主索引鍵值。

  主索引鍵可以是*簡單的*，包含單一分割區 (HASH) 索引鍵；也可以是*複合的*，包含分割區和排序 (RANGE) 索引鍵。

  每個索引鍵值都有一個關聯的*資料類型*，由 [ScalarAttributeType](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/namespace_aws_1_1_dynamo_d_b_1_1_model.html#a4b39ae66214e022d3737079d071e4bcb.html) 類別列舉。索引鍵值可以是二進位 (B)、數值 (N)、或字串 (S)。如需詳細資訊，請參閱《Amazon DynamoDB 開發人員指南》中的[命名規則和資料類型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html)。
+  定義資料表預留讀取/寫入容量單位數量的*佈建輸送量*值。
**注意**  
 [Amazon DynamoDB 定價](https://aws.amazon.com/dynamodb/pricing/)是根據您對資料表設定的佈建輸送量值，所以請只預留您認為您的資料表需要的容量。  
資料表的佈建輸送量可以隨時修改，因此您可以在需要變更時調整容量。

## 建立資料表
<a name="dynamodb-create-table"></a>

使用 [DynamoDB 用戶端](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)`CreateTable`方法來建立新的 DynamoDB 資料表。您需要建構資料表屬性和資料表結構描述，這兩項都會用來識別資料表的主索引鍵。您也必須提供初始佈建輸送量值和資料表名稱。 `CreateTable` 是非同步操作。 `GetTableStatus`會傳回 CREATING，直到資料表處於 ACTIVE 且可供使用為止。

### 使用簡單主索引鍵建立資料表
<a name="dynamodb-create-table-simple"></a>

此程式碼會使用簡單主索引鍵 ("Name") 來建立資料表。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>
```

 **Code** 

```
//! Create an Amazon DynamoDB table.
/*!
  \sa createTable()
  \param tableName: Name for the DynamoDB table.
  \param primaryKey: Primary key for the DynamoDB table.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTable(const Aws::String &tableName,
                                   const Aws::String &primaryKey,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a simple primary key: \"" << primaryKey << "\"." << std::endl;

    Aws::DynamoDB::Model::CreateTableRequest request;

    Aws::DynamoDB::Model::AttributeDefinition hashKey;
    hashKey.SetAttributeName(primaryKey);
    hashKey.SetAttributeType(Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement;
    keySchemaElement.WithAttributeName(primaryKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement);

    Aws::DynamoDB::Model::ProvisionedThroughput throughput;
    throughput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
    request.SetProvisionedThroughput(throughput);
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::CreateTableOutcome &outcome = dynamoClient.CreateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Table \""
                  << outcome.GetResult().GetTableDescription().GetTableName() <<
                  " created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table: " << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table.cpp)。

### 使用複合主索引鍵建立資料表
<a name="dynamodb-create-table-composite"></a>

新增另一個 [AttributeDefinition](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_definition.html) 和 [KeySchemaElement](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_key_schema_element.html) 到 [CreateTableRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_create_table_request.html)。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/CreateTableRequest.h>
#include <aws/dynamodb/model/KeySchemaElement.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/ScalarAttributeType.h>
#include <iostream>
```

 **Code** 

```
//! Create an Amazon DynamoDB table with a composite key.
/*!
  \sa createTableWithCompositeKey()
  \param tableName: Name for the DynamoDB table.
  \param partitionKey: Name for the partition (hash) key.
  \param sortKey: Name for the sort (range) key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::createTableWithCompositeKey(const Aws::String &tableName,
                                                   const Aws::String &partitionKey,
                                                   const Aws::String &sortKey,
                                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Creating table " << tableName <<
              " with a composite primary key:\n" \
            "* " << partitionKey << " - partition key\n" \
            "* " << sortKey << " - sort key\n";

    Aws::DynamoDB::Model::CreateTableRequest request;

    Aws::DynamoDB::Model::AttributeDefinition hashKey1, hashKey2;
    hashKey1.WithAttributeName(partitionKey).WithAttributeType(
            Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey1);
    hashKey2.WithAttributeName(sortKey).WithAttributeType(
            Aws::DynamoDB::Model::ScalarAttributeType::S);
    request.AddAttributeDefinitions(hashKey2);

    Aws::DynamoDB::Model::KeySchemaElement keySchemaElement1, keySchemaElement2;
    keySchemaElement1.WithAttributeName(partitionKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::HASH);
    request.AddKeySchema(keySchemaElement1);
    keySchemaElement2.WithAttributeName(sortKey).WithKeyType(
            Aws::DynamoDB::Model::KeyType::RANGE);
    request.AddKeySchema(keySchemaElement2);

    Aws::DynamoDB::Model::ProvisionedThroughput throughput;
    throughput.WithReadCapacityUnits(5).WithWriteCapacityUnits(5);
    request.SetProvisionedThroughput(throughput);

    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::CreateTableOutcome &outcome = dynamoClient.CreateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Table \""
                  << outcome.GetResult().GetTableDescription().GetTableName() <<
                  "\" was created!" << std::endl;
    }
    else {
        std::cerr << "Failed to create table:" << outcome.GetError().GetMessage()
                  << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table_composite_key.cpp)。

## 列出資料表
<a name="dynamodb-list-tables"></a>

您可以呼叫 [DynamoDB 用戶端](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)`ListTables`方法，列出特定區域中的資料表。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ListTablesRequest.h>
#include <aws/dynamodb/model/ListTablesResult.h>
#include <iostream>
```

 **Code** 

```
//! List the Amazon DynamoDB tables for the current AWS account.
/*!
  \sa listTables()
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::listTables(
        const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::ListTablesRequest listTablesRequest;
    listTablesRequest.SetLimit(50);
    do {
        const Aws::DynamoDB::Model::ListTablesOutcome &outcome = dynamoClient.ListTables(
                listTablesRequest);
        if (!outcome.IsSuccess()) {
            std::cout << "Error: " << outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        for (const auto &tableName: outcome.GetResult().GetTableNames())
            std::cout << tableName << std::endl;
        listTablesRequest.SetExclusiveStartTableName(
                outcome.GetResult().GetLastEvaluatedTableName());

    } while (!listTablesRequest.GetExclusiveStartTableName().empty());

    return true;
}
```

根據預設，每次呼叫最多傳回 100 個資料表。在傳回的 [ListTablesOutcome](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html) 物件`GetExclusiveStartTableName`上使用 ，以取得上次評估的資料表。您可以使用這個值，在前次列表最後傳回值之後開始列表。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/list_tables.cpp)。

## 擷取資料表的相關資訊
<a name="dynamodb-describe-table"></a>

您可以呼叫 [DynamoDB 用戶端](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)`DescribeTable`方法，進一步了解資料表。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/DescribeTableRequest.h>
#include <iostream>
```

 **Code** 

```
//! Describe an Amazon DynamoDB table.
/*!
  \sa describeTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::describeTable(const Aws::String &tableName,
                                     const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DescribeTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DescribeTableOutcome &outcome = dynamoClient.DescribeTable(
            request);

    if (outcome.IsSuccess()) {
        const Aws::DynamoDB::Model::TableDescription &td = outcome.GetResult().GetTable();
        std::cout << "Table name  : " << td.GetTableName() << std::endl;
        std::cout << "Table ARN   : " << td.GetTableArn() << std::endl;
        std::cout << "Status      : "
                  << Aws::DynamoDB::Model::TableStatusMapper::GetNameForTableStatus(
                          td.GetTableStatus()) << std::endl;
        std::cout << "Item count  : " << td.GetItemCount() << std::endl;
        std::cout << "Size (bytes): " << td.GetTableSizeBytes() << std::endl;

        const Aws::DynamoDB::Model::ProvisionedThroughputDescription &ptd = td.GetProvisionedThroughput();
        std::cout << "Throughput" << std::endl;
        std::cout << "  Read Capacity : " << ptd.GetReadCapacityUnits() << std::endl;
        std::cout << "  Write Capacity: " << ptd.GetWriteCapacityUnits() << std::endl;

        const Aws::Vector<Aws::DynamoDB::Model::AttributeDefinition> &ad = td.GetAttributeDefinitions();
        std::cout << "Attributes" << std::endl;
        for (const auto &a: ad)
            std::cout << "  " << a.GetAttributeName() << " (" <<
                      Aws::DynamoDB::Model::ScalarAttributeTypeMapper::GetNameForScalarAttributeType(
                              a.GetAttributeType()) <<
                      ")" << std::endl;
    }
    else {
        std::cerr << "Failed to describe table: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/describe_table.cpp)。

## 修改資料表
<a name="dynamodb-update-table"></a>

您可以隨時呼叫 [DynamoDB 用戶端](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)`UpdateTable`方法，修改資料表的佈建輸送量值。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/Outcome.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/ProvisionedThroughput.h>
#include <aws/dynamodb/model/UpdateTableRequest.h>
#include <iostream>
```

 **Code** 

```
//! Update a DynamoDB table.
/*!
  \sa updateTable()
  \param tableName: Name for the DynamoDB table.
  \param readCapacity: Provisioned read capacity.
  \param writeCapacity: Provisioned write capacity.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::updateTable(const Aws::String &tableName,
                                   long long readCapacity, long long writeCapacity,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    std::cout << "Updating " << tableName << " with new provisioned throughput values"
              << std::endl;
    std::cout << "Read capacity : " << readCapacity << std::endl;
    std::cout << "Write capacity: " << writeCapacity << std::endl;

    Aws::DynamoDB::Model::UpdateTableRequest request;
    Aws::DynamoDB::Model::ProvisionedThroughput provisionedThroughput;
    provisionedThroughput.WithReadCapacityUnits(readCapacity).WithWriteCapacityUnits(
            writeCapacity);
    request.WithProvisionedThroughput(provisionedThroughput).WithTableName(tableName);

    const Aws::DynamoDB::Model::UpdateTableOutcome &outcome = dynamoClient.UpdateTable(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated the table." << std::endl;
    } else {
        const Aws::DynamoDB::DynamoDBError &error = outcome.GetError();
        if (error.GetErrorType() == Aws::DynamoDB::DynamoDBErrors::VALIDATION &&
            error.GetMessage().find("The provisioned throughput for the table will not change") != std::string::npos) {
            std::cout << "The provisioned throughput for the table will not change." << std::endl;
        } else {
            std::cerr << outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }

    return waitTableActive(tableName, dynamoClient);
}
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/update_table.cpp)。

## 刪除資料表
<a name="dynamodb-delete-table"></a>

呼叫 [DynamoDB 用戶端](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)`DeleteTable`方法並傳遞資料表的名稱。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/DeleteTableRequest.h>
#include <iostream>
```

 **Code** 

```
//! Delete an Amazon DynamoDB table.
/*!
  \sa deleteTable()
  \param tableName: The DynamoDB table name.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
*/
bool AwsDoc::DynamoDB::deleteTable(const Aws::String &tableName,
                                   const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::DeleteTableRequest request;
    request.SetTableName(tableName);

    const Aws::DynamoDB::Model::DeleteTableOutcome &result = dynamoClient.DeleteTable(
            request);
    if (result.IsSuccess()) {
        std::cout << "Your table \""
                  << result.GetResult().GetTableDescription().GetTableName()
                  << " was deleted.\n";
    }
    else {
        std::cerr << "Failed to delete table: " << result.GetError().GetMessage()
                  << std::endl;
    }

    return result.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/delete_table.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  《Amazon DynamoDB 開發人員指南》中的[使用資料表的指導方針](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html) 
+  《Amazon[ DynamoDB 開發人員指南》中的使用 DynamoDB 中的資料表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithTables.html) DynamoDB 

# 在 DynamoDB 中使用項目
<a name="examples-dynamodb-items"></a>

在 DynamoDB 中，項目是*屬性*的集合，每個屬性都有*名稱*和*值*。屬性值可以是純量、集合或文件類型。如需詳細資訊，請參閱《Amazon DynamoDB 開發人員指南》中的[命名規則和資料類型](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html)。

## 從資料表擷取項目
<a name="dynamodb-get-item"></a>

呼叫 [DynamoDB 用戶端](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_dynamo_d_b_client.html)`GetItem`方法。傳遞 [GetItemRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_get_item_request.html) 物件，其中包含您想要的項目的資料表名稱和主索引鍵值。它傳回 [GetItemResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_get_item_result.html) 物件。

您可以使用傳回`GetItemResult`物件的 `GetItem()`方法，擷取與項目相關聯的`Aws::Map`金鑰`Aws::String`和值 [AttributeValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_value.html) 對的 。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/GetItemRequest.h>
#include <iostream>
```

 **Code** 

```
//! Get an item from an Amazon DynamoDB table.
/*!
  \sa getItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */

bool AwsDoc::DynamoDB::getItem(const Aws::String &tableName,
                               const Aws::String &partitionKey,
                               const Aws::String &partitionValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);
    Aws::DynamoDB::Model::GetItemRequest request;

    // Set up the request.
    request.SetTableName(tableName);
    request.AddKey(partitionKey,
                   Aws::DynamoDB::Model::AttributeValue().SetS(partitionValue));

    // Retrieve the item's fields and values.
    const Aws::DynamoDB::Model::GetItemOutcome &outcome = dynamoClient.GetItem(request);
    if (outcome.IsSuccess()) {
        // Reference the retrieved fields/values.
        const Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> &item = outcome.GetResult().GetItem();
        if (!item.empty()) {
            // Output each retrieved field and its value.
            for (const auto &i: item)
                std::cout << "Values: " << i.first << ": " << i.second.GetS()
                          << std::endl;
        }
        else {
            std::cout << "No item found with the key " << partitionKey << std::endl;
        }
    }
    else {
        std::cerr << "Failed to get item: " << outcome.GetError().GetMessage();
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/get_item.cpp)。

## 將項目新增至資料表
<a name="dynamodb-add-item"></a>

建立代表每個項目的索引鍵`Aws::String`和值 [AttributeValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_attribute_value.html) 對。這些項目必須包含資料表主索引鍵欄位的值。如果主索引鍵識別的項目已存在，其欄位會透過請求*更新*。使用 `AddItem`方法將它們新增至 [PutItemRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-dynamodb/html/class_aws_1_1_dynamo_d_b_1_1_model_1_1_put_item_request.html)。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/AttributeDefinition.h>
#include <aws/dynamodb/model/PutItemRequest.h>
#include <aws/dynamodb/model/PutItemResult.h>
#include <iostream>
```

 **Code** 

```
//! Put an item in an Amazon DynamoDB table.
/*!
  \sa putItem()
  \param tableName: The table name.
  \param artistKey: The artist key. This is the partition key for the table.
  \param artistValue: The artist value.
  \param albumTitleKey: The album title key.
  \param albumTitleValue: The album title value.
  \param awardsKey: The awards key.
  \param awardsValue: The awards value.
  \param songTitleKey: The song title key.
  \param songTitleValue: The song title value.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::DynamoDB::putItem(const Aws::String &tableName,
                               const Aws::String &artistKey,
                               const Aws::String &artistValue,
                               const Aws::String &albumTitleKey,
                               const Aws::String &albumTitleValue,
                               const Aws::String &awardsKey,
                               const Aws::String &awardsValue,
                               const Aws::String &songTitleKey,
                               const Aws::String &songTitleValue,
                               const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    Aws::DynamoDB::Model::PutItemRequest putItemRequest;
    putItemRequest.SetTableName(tableName);

    putItemRequest.AddItem(artistKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            artistValue)); // This is the hash key.
    putItemRequest.AddItem(albumTitleKey, Aws::DynamoDB::Model::AttributeValue().SetS(
            albumTitleValue));
    putItemRequest.AddItem(awardsKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(awardsValue));
    putItemRequest.AddItem(songTitleKey,
                           Aws::DynamoDB::Model::AttributeValue().SetS(songTitleValue));

    const Aws::DynamoDB::Model::PutItemOutcome outcome = dynamoClient.PutItem(
            putItemRequest);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully added Item!" << std::endl;
    }
    else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/put_item.cpp)。

## 更新資料表中的現有項目
<a name="dynamodb-update-item"></a>

您可以使用 DynamoDBClient 的 `UpdateItem`方法，提供資料表名稱、主索引鍵值和要更新的欄位及其對應值，來更新已存在於資料表中的項目屬性。

 **匯入** 

```
#include <aws/core/Aws.h>
#include <aws/dynamodb/DynamoDBClient.h>
#include <aws/dynamodb/model/UpdateItemRequest.h>
#include <aws/dynamodb/model/UpdateItemResult.h>
#include <iostream>
```

 **Code** 

```
//! Update an Amazon DynamoDB table item.
/*!
  \sa updateItem()
  \param tableName: The table name.
  \param partitionKey: The partition key.
  \param partitionValue: The value for the partition key.
  \param attributeKey: The key for the attribute to be updated.
  \param attributeValue: The value for the attribute to be updated.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
  */

/*
 *  The example code only sets/updates an attribute value. It processes
 *  the attribute value as a string, even if the value could be interpreted
 *  as a number. Also, the example code does not remove an existing attribute
 *  from the key value.
 */

bool AwsDoc::DynamoDB::updateItem(const Aws::String &tableName,
                                  const Aws::String &partitionKey,
                                  const Aws::String &partitionValue,
                                  const Aws::String &attributeKey,
                                  const Aws::String &attributeValue,
                                  const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::DynamoDB::DynamoDBClient dynamoClient(clientConfiguration);

    // *** Define UpdateItem request arguments.
    // Define TableName argument.
    Aws::DynamoDB::Model::UpdateItemRequest request;
    request.SetTableName(tableName);

    // Define KeyName argument.
    Aws::DynamoDB::Model::AttributeValue attribValue;
    attribValue.SetS(partitionValue);
    request.AddKey(partitionKey, attribValue);

    // Construct the SET update expression argument.
    Aws::String update_expression("SET #a = :valueA");
    request.SetUpdateExpression(update_expression);

    // Construct attribute name argument.
    Aws::Map<Aws::String, Aws::String> expressionAttributeNames;
    expressionAttributeNames["#a"] = attributeKey;
    request.SetExpressionAttributeNames(expressionAttributeNames);

    // Construct attribute value argument.
    Aws::DynamoDB::Model::AttributeValue attributeUpdatedValue;
    attributeUpdatedValue.SetS(attributeValue);
    Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> expressionAttributeValues;
    expressionAttributeValues[":valueA"] = attributeUpdatedValue;
    request.SetExpressionAttributeValues(expressionAttributeValues);

    // Update the item.
    const Aws::DynamoDB::Model::UpdateItemOutcome &outcome = dynamoClient.UpdateItem(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Item was updated" << std::endl;
    } else {
        std::cerr << outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    return waitTableActive(tableName, dynamoClient);
}
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/update_item.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  《Amazon DynamoDB 開發人員指南》中的[使用項目的指導方針](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForItems.html) 
+  《Amazon[ DynamoDB 開發人員指南》中的使用 DynamoDB 中的項目](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html) DynamoDB 

# 使用 的 Amazon EC2 範例 適用於 C\$1\$1 的 AWS SDK
<a name="examples-ec2"></a>

Amazon Elastic Compute Cloud (Amazon EC2) 是一種 Web 服務，可提供可調整大小的運算容量，通常是 Amazon 資料中心的伺服器，可用來建置和託管軟體系統。您可以使用下列範例，使用 編寫 [Amazon EC2](https://aws.amazon.com/ec2) 的程式 適用於 C\$1\$1 的 AWS SDK。

**注意**  
本指南僅提供示範特定技術所需的程式碼，但[完整的範例程式碼可在 GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。在 GitHub 上，您可以下載單一來源檔案，也可以在本機複製儲存庫，以取得、建置和執行所有範例。

**Topics**
+ [管理 Amazon EC2 執行個體](examples-ec2-instances.md)
+ [在 Amazon EC2 中使用彈性 IP 地址](examples-ec2-elastic-ip.md)
+ [使用 Amazon EC2 的區域與可用區域](examples-ec2-regions-zones.md)
+ [使用 Amazon EC2 金鑰對](examples-ec2-key-pairs.md)
+ [在 Amazon EC2 中使用安全群組](examples-ec2-security-groups.md)

# 管理 Amazon EC2 執行個體
<a name="examples-ec2-instances"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立 執行個體
<a name="create-an-instance"></a>

透過呼叫 EC2Client 的 `RunInstances`函數建立新的 Amazon EC2 執行個體，為其提供 [RunInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_run_instances_request.html)，其中包含要使用的 [Amazon Machine Image (AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) 和[執行個體類型](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/RunInstancesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::RunInstancesRequest runRequest;
    runRequest.SetImageId(amiId);
    runRequest.SetInstanceType(Aws::EC2::Model::InstanceType::t1_micro);
    runRequest.SetMinCount(1);
    runRequest.SetMaxCount(1);

    Aws::EC2::Model::RunInstancesOutcome runOutcome = ec2Client.RunInstances(
            runRequest);
    if (!runOutcome.IsSuccess()) {
        std::cerr << "Failed to launch EC2 instance " << instanceName <<
                  " based on ami " << amiId << ":" <<
                  runOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    const Aws::Vector<Aws::EC2::Model::Instance> &instances = runOutcome.GetResult().GetInstances();
    if (instances.empty()) {
        std::cerr << "Failed to launch EC2 instance " << instanceName <<
                  " based on ami " << amiId << ":" <<
                  runOutcome.GetError().GetMessage() << std::endl;
        return false;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/run_instances.cpp)。

## 啟動執行個體
<a name="start-an-instance"></a>

若要啟動 Amazon EC2 執行個體，請呼叫 EC2Client 的 `StartInstances`函數，為其提供 [StartInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_start_instances_request.html)，其中包含要啟動的執行個體 ID。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/StartInstancesRequest.h>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::StartInstancesRequest startRequest;
    startRequest.AddInstanceIds(instanceId);
    startRequest.SetDryRun(true);

    Aws::EC2::Model::StartInstancesOutcome dryRunOutcome = ec2Client.StartInstances(startRequest);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to start instance. A dry run should trigger an error."
                << std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to start instance " << instanceId << ": "
                  << dryRunOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    startRequest.SetDryRun(false);
    Aws::EC2::Model::StartInstancesOutcome startInstancesOutcome = ec2Client.StartInstances(startRequest);

    if (!startInstancesOutcome.IsSuccess()) {
        std::cout << "Failed to start instance " << instanceId << ": " <<
                  startInstancesOutcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully started instance " << instanceId <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/start_stop_instance.cpp)。

## 停止執行個體
<a name="stop-an-instance"></a>

若要停止 Amazon EC2 執行個體，請呼叫 EC2Client 的 `StopInstances`函數，為其提供 [StopInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_stop_instances_request.html)，其中包含要停止的執行個體 ID。

 **包括** 

```
#include <aws/ec2/model/StopInstancesRequest.h>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::StopInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::StopInstancesOutcome dryRunOutcome = ec2Client.StopInstances(request);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to stop instance. A dry run should trigger an error."
                << std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to stop instance " << instanceId << ": "
                  << dryRunOutcome.GetError().GetMessage() << std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::StopInstancesOutcome outcome = ec2Client.StopInstances(request);
    if (!outcome.IsSuccess()) {
        std::cout << "Failed to stop instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully stopped instance " << instanceId <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/start_stop_instance.cpp)。

## 重新啟動執行個體
<a name="reboot-an-instance"></a>

若要重新啟動 Amazon EC2 執行個體，請呼叫 EC2Client 的 `RebootInstances`函數，為其提供 [RebootInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_reboot_instances_request.html)，其中包含要重新啟動的執行個體 ID。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/RebootInstancesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::RebootInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::RebootInstancesOutcome dry_run_outcome = ec2Client.RebootInstances(request);
    if (dry_run_outcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to reboot on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dry_run_outcome.GetError().GetErrorType()
               != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to reboot instance " << instanceId << ": "
                  << dry_run_outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::RebootInstancesOutcome outcome = ec2Client.RebootInstances(request);
    if (!outcome.IsSuccess()) {
        std::cout << "Failed to reboot instance " << instanceId << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully rebooted instance " << instanceId <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/reboot_instance.cpp)。

## 描述執行個體
<a name="describe-instances"></a>

若要列出您的執行個體，請建立 [DescribeInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_instances_request.html) 並呼叫 EC2Client 的 `DescribeInstances`函數。它會傳回 [DescribeInstancesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_instances_response.html) 物件，您可以用來列出 AWS 帳戶 和 的 Amazon EC2 執行個體 AWS 區域。

執行個體依照*保留*分組。每個保留對應到呼叫 `StartInstances`，用以啟動執行個體。若要列出您的執行個體，您必須先呼叫`DescribeInstancesResponse`類別的 `GetReservations`函數，然後在每個傳回的預留物件`getInstances`上呼叫 。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeInstancesRequest.h>
#include <aws/ec2/model/DescribeInstancesResponse.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeInstancesRequest request;
    bool header = false;
    bool done = false;
    while (!done) {
        Aws::EC2::Model::DescribeInstancesOutcome outcome = ec2Client.DescribeInstances(request);
        if (outcome.IsSuccess()) {
            if (!header) {
                std::cout << std::left <<
                          std::setw(48) << "Name" <<
                          std::setw(20) << "ID" <<
                          std::setw(25) << "Ami" <<
                          std::setw(15) << "Type" <<
                          std::setw(15) << "State" <<
                          std::setw(15) << "Monitoring" << std::endl;
                header = true;
            }

            const std::vector<Aws::EC2::Model::Reservation> &reservations =
                    outcome.GetResult().GetReservations();

            for (const auto &reservation: reservations) {
                const std::vector<Aws::EC2::Model::Instance> &instances =
                        reservation.GetInstances();
                for (const auto &instance: instances) {
                    Aws::String instanceStateString =
                            Aws::EC2::Model::InstanceStateNameMapper::GetNameForInstanceStateName(
                                    instance.GetState().GetName());

                    Aws::String typeString =
                            Aws::EC2::Model::InstanceTypeMapper::GetNameForInstanceType(
                                    instance.GetInstanceType());

                    Aws::String monitorString =
                            Aws::EC2::Model::MonitoringStateMapper::GetNameForMonitoringState(
                                    instance.GetMonitoring().GetState());
                    Aws::String name = "Unknown";

                    const std::vector<Aws::EC2::Model::Tag> &tags = instance.GetTags();
                    auto nameIter = std::find_if(tags.cbegin(), tags.cend(),
                                                 [](const Aws::EC2::Model::Tag &tag) {
                                                     return tag.GetKey() == "Name";
                                                 });
                    if (nameIter != tags.cend()) {
                        name = nameIter->GetValue();
                    }
                    std::cout <<
                              std::setw(48) << name <<
                              std::setw(20) << instance.GetInstanceId() <<
                              std::setw(25) << instance.GetImageId() <<
                              std::setw(15) << typeString <<
                              std::setw(15) << instanceStateString <<
                              std::setw(15) << monitorString << std::endl;
                }
            }

            if (!outcome.GetResult().GetNextToken().empty()) {
                request.SetNextToken(outcome.GetResult().GetNextToken());
            } else {
                done = true;
            }
        } else {
            std::cerr << "Failed to describe EC2 instances:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }
    }
```

結果是分頁的；您可以將結果物件的 `GetNextToken`函數傳回的值傳遞至原始請求物件的 `SetNextToken` 函數，然後在下一次呼叫 時使用相同的請求物件，以取得進一步的結果`DescribeInstances`。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_instances.cpp)。

## 啟用執行個體監控
<a name="enable-instance-monitoring"></a>

您可以監控 Amazon EC2 執行個體的各個層面，例如 CPU 和網路使用率、可用的記憶體，以及剩餘的磁碟空間。若要進一步了解執行個體監控，請參閱《[Amazon EC2 使用者指南》中的監控](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring_ec2.html) Amazon EC2。

若要開始監控執行個體，您必須使用要監控的執行個體 ID 建立 [MonitorInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_monitor_instances_request.html)，並將其傳遞給 EC2Client 的 `MonitorInstances`函數。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/MonitorInstancesRequest.h>
#include <aws/ec2/model/UnmonitorInstancesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::MonitorInstancesRequest request;
    request.AddInstanceIds(instanceId);
    request.SetDryRun(true);

    Aws::EC2::Model::MonitorInstancesOutcome dryRunOutcome = ec2Client.MonitorInstances(request);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to enable monitoring on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType()
               != Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cerr << "Failed dry run to enable monitoring on instance " <<
                  instanceId << ": " << dryRunOutcome.GetError().GetMessage() <<
                  std::endl;
        return false;
    }

    request.SetDryRun(false);
    Aws::EC2::Model::MonitorInstancesOutcome monitorInstancesOutcome = ec2Client.MonitorInstances(request);
    if (!monitorInstancesOutcome.IsSuccess()) {
        std::cerr << "Failed to enable monitoring on instance " <<
                  instanceId << ": " <<
                  monitorInstancesOutcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully enabled monitoring on instance " <<
                  instanceId << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/monitor_instance.cpp)。

## 停用執行個體監控
<a name="disable-instance-monitoring"></a>

若要停止監控執行個體，請使用執行個體的 ID 建立 [UnmonitorInstancesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_unmonitor_instances_request.html) 以停止監控，並將其傳遞給 EC2Client 的 `UnmonitorInstances`函數。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/MonitorInstancesRequest.h>
#include <aws/ec2/model/UnmonitorInstancesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::UnmonitorInstancesRequest unrequest;
    unrequest.AddInstanceIds(instanceId);
    unrequest.SetDryRun(true);

    Aws::EC2::Model::UnmonitorInstancesOutcome dryRunOutcome = ec2Client.UnmonitorInstances(unrequest);
    if (dryRunOutcome.IsSuccess()) {
        std::cerr
                << "Failed dry run to disable monitoring on instance. A dry run should trigger an error."
                <<
                std::endl;
        return false;
    } else if (dryRunOutcome.GetError().GetErrorType() !=
               Aws::EC2::EC2Errors::DRY_RUN_OPERATION) {
        std::cout << "Failed dry run to disable monitoring on instance " <<
                  instanceId << ": " << dryRunOutcome.GetError().GetMessage() <<
                  std::endl;
        return false;
    }

    unrequest.SetDryRun(false);
    Aws::EC2::Model::UnmonitorInstancesOutcome unmonitorInstancesOutcome = ec2Client.UnmonitorInstances(unrequest);
    if (!unmonitorInstancesOutcome.IsSuccess()) {
        std::cout << "Failed to disable monitoring on instance " << instanceId
                  << ": " << unmonitorInstancesOutcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully disable monitoring on instance " <<
                  instanceId << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/monitor_instance.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  Amazon EC2 API 參考中的 [RunInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RunInstances.html) 
+  Amazon EC2 API 參考中的 [DescribeInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) 
+  Amazon EC2 API 參考中的 [StartInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_StartInstances.html) 
+  Amazon EC2 API 參考中的 [StopInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_StopInstances.html) 
+  Amazon EC2 API 參考中的 [RebootInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_RebootInstances.html) 
+  Amazon EC2 API 參考中的 [DescribeInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInstances.html) 
+  Amazon EC2 API 參考中的 [MonitorInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_MonitorInstances.html) 
+  Amazon EC2 API 參考中的 [UnmonitorInstances](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_UnmonitorInstances.html) 

# 在 Amazon EC2 中使用彈性 IP 地址
<a name="examples-ec2-elastic-ip"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 配置彈性 IP 地址
<a name="allocate-an-elastic-ip-address"></a>

若要使用彈性 IP 位址，您可以先將一個地址配置給帳戶，再將其與您的執行個體或網路介面建立關聯。

若要配置彈性 IP 地址，請使用包含 網路類型的 [AllocateAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_allocate_address_request.html) 物件 （傳統 EC2 或 VPC) 呼叫 EC2Client 的 `AllocateAddress`函數。

**警告**  
我們將於 2022 年 8 月 15 日淘汰 EC2-Classic。建議您從 EC2-Classic 遷移至 VPC。如需詳細資訊，請參閱《Amazon ** EC2 Linux 執行個體使用者指南》或《Amazon EC2 Windows 執行個體使用者指南》中的從 EC2-Classic 遷移至 VPC**。 [Amazon EC2 ](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html) [Amazon EC2 ](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/vpc-migrate.html) 也請參閱部落格文章 [EC2-Classic 網路正在淘汰 - 本文介紹如何準備](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/)。

回應物件中的 [AllocateAddressResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_allocate_address_response.html) 類別包含一個配置 ID，您可以將 [AssociateAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_associate_address_request.html) 中的配置 ID 和執行個體 ID 傳遞至 EC2Client 的 `AssociateAddress`函數，藉此將地址與執行個體建立關聯。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/AllocateAddressRequest.h>
#include <aws/ec2/model/AssociateAddressRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::AllocateAddressRequest request;
    request.SetDomain(Aws::EC2::Model::DomainType::vpc);

    const Aws::EC2::Model::AllocateAddressOutcome outcome =
            ec2Client.AllocateAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to allocate Elastic IP address:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }
    const Aws::EC2::Model::AllocateAddressResponse &response = outcome.GetResult();
    allocationID = response.GetAllocationId();
    publicIPAddress = response.GetPublicIp();


    Aws::EC2::Model::AssociateAddressRequest associate_request;
    associate_request.SetInstanceId(instanceId);
    associate_request.SetAllocationId(allocationID);

    const Aws::EC2::Model::AssociateAddressOutcome associate_outcome =
            ec2Client.AssociateAddress(associate_request);
    if (!associate_outcome.IsSuccess()) {
        std::cerr << "Failed to associate Elastic IP address " << allocationID
                  << " with instance " << instanceId << ":" <<
                  associate_outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    std::cout << "Successfully associated Elastic IP address " << allocationID
              << " with instance " << instanceId << std::endl;
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/allocate_address.cpp)。

## 說明彈性 IP 地址
<a name="describe-elastic-ip-addresses"></a>

若要列出指派給您帳戶的彈性 IP 地址，請呼叫 EC2Client 的 `DescribeAddresses`函數。它會傳回結果物件，其中包含 [DescribeAddressesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_addresses_response.html)，可用來取得代表您帳戶中彈性 IP 地址的[位址](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_address.html)物件清單。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeAddressesRequest.h>
#include <aws/ec2/model/DescribeAddressesResponse.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeAddressesRequest request;
    Aws::EC2::Model::DescribeAddressesOutcome outcome = ec2Client.DescribeAddresses(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left << std::setw(20) << "InstanceId" <<
                  std::setw(15) << "Public IP" << std::setw(10) << "Domain" <<
                  std::setw(30) << "Allocation ID" << std::setw(25) <<
                  "NIC ID" << std::endl;

        const Aws::Vector<Aws::EC2::Model::Address> &addresses = outcome.GetResult().GetAddresses();
        for (const auto &address: addresses) {
            Aws::String domainString =
                    Aws::EC2::Model::DomainTypeMapper::GetNameForDomainType(
                            address.GetDomain());

            std::cout << std::left << std::setw(20) <<
                      address.GetInstanceId() << std::setw(15) <<
                      address.GetPublicIp() << std::setw(10) << domainString <<
                      std::setw(30) << address.GetAllocationId() << std::setw(25)
                      << address.GetNetworkInterfaceId() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe Elastic IP addresses:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_addresses.cpp)。

## 釋出彈性 IP 地址
<a name="release-an-elastic-ip-address"></a>

若要釋出彈性 IP 地址，請呼叫 EC2Client 的 `ReleaseAddress`函數，並向其傳遞 [ReleaseAddressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_release_address_request.html)，其中包含您要釋出之彈性 IP 地址的配置 ID。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/ReleaseAddressRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2(clientConfiguration);

    Aws::EC2::Model::ReleaseAddressRequest request;
    request.SetAllocationId(allocationID);

    Aws::EC2::Model::ReleaseAddressOutcome outcome = ec2.ReleaseAddress(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to release Elastic IP address " <<
                  allocationID << ":" << outcome.GetError().GetMessage() <<
                  std::endl;
    } else {
        std::cout << "Successfully released Elastic IP address " <<
                  allocationID << std::endl;
    }
```

釋出彈性 IP 地址後，該地址會釋出到 AWS IP 地址集區，您之後可能無法使用。請務必更新您的 DNS 記錄以及與該地址通訊的任何伺服器或裝置。如果您嘗試釋出已發行的彈性 IP 地址，如果地址已配置給另一個 AWS 帳戶，則會收到 *AuthFailure* 錯誤。

如果您使用的是*預設 VPC*，則釋放彈性 IP 地址會自動將其與與其相關聯的任何執行個體取消關聯。若要取消彈性 IP 地址的關聯而不釋出，請使用 EC2Client 的 `DisassociateAddress`函數。

如果您是使用非預設 VPC，在嘗試釋出該彈性 IP 地址前，您*必須*先使用 `DisassociateAddress` 將其取消關聯。否則，Amazon EC2 會傳回錯誤 (*InvalidIPAddress.InUse*)。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/release_address.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《Amazon EC2 使用者指南》中的[彈性 IP 地址](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) 
+  Amazon EC2 API 參考中的 [AllocateAddress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AllocateAddress.html) 
+  Amazon EC2 API 參考中的 [DescribeAddresses](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAddresses.html) 
+  Amazon EC2 API 參考中的 [ReleaseAddress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ReleaseAddress.html) 

# 使用 Amazon EC2 的區域與可用區域
<a name="examples-ec2-regions-zones"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 描述區域
<a name="describe-regions"></a>

若要列出您的 AWS 區域 可用 AWS 帳戶，請使用 [DescribeRegionsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_regions_request.html) 呼叫 EC2Client 的 `DescribeRegions`函數。

您會在結果物件中收到 [DescribeRegionsResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_regions_response.html)。呼叫其`GetRegions`函數以取得代表每個[區域的](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_region.html)區域物件清單。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeRegionsRequest.h>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::DescribeRegionsRequest request;
    Aws::EC2::Model::DescribeRegionsOutcome outcome = ec2Client.DescribeRegions(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "RegionName" <<
                  std::setw(64) << "Endpoint" << std::endl;

        const auto &regions = outcome.GetResult().GetRegions();
        for (const auto &region: regions) {
            std::cout << std::left <<
                      std::setw(32) << region.GetRegionName() <<
                      std::setw(64) << region.GetEndpoint() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe regions:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_regions_and_zones.cpp)。

## 描述可用區域
<a name="describe-availability-zones"></a>

若要列出您帳戶可用的每個可用區域，請使用 [DescribeAvailabilityZonesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_availability_zones_request.html) 呼叫 EC2Client 的 `DescribeAvailabilityZones`函數。

您會在結果物件中收到 [DescribeAvailabilityZonesResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_availability_zones_response.html)。呼叫其 `GetAvailabilityZones` 函數以取得代表每個可用區域的 [AvailabilityZone](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_availability_zone.html) 物件清單。

 **包括** 

```
#include <aws/ec2/model/DescribeAvailabilityZonesRequest.h>
```

 **Code** 

```
    Aws::EC2::Model::DescribeAvailabilityZonesRequest request;
    Aws::EC2::Model::DescribeAvailabilityZonesOutcome outcome = ec2Client.DescribeAvailabilityZones(request);

    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "ZoneName" <<
                  std::setw(20) << "State" <<
                  std::setw(32) << "Region" << std::endl;

        const auto &zones =
                outcome.GetResult().GetAvailabilityZones();

        for (const auto &zone: zones) {
            Aws::String stateString =
                    Aws::EC2::Model::AvailabilityZoneStateMapper::GetNameForAvailabilityZoneState(
                            zone.GetState());
            std::cout << std::left <<
                      std::setw(32) << zone.GetZoneName() <<
                      std::setw(20) << stateString <<
                      std::setw(32) << zone.GetRegionName() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe availability zones:" <<
                  outcome.GetError().GetMessage() << std::endl;

    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_regions_and_zones.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《Amazon EC2 使用者指南》中的[區域和可用區域](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-regions-availability-zones.html) 
+  Amazon EC2 API 參考中的 [DescribeRegions](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeRegions.html) 
+  Amazon EC2 API 參考中的 [DescribeAvailabilityZones](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeAvailabilityZones.html) 

# 使用 Amazon EC2 金鑰對
<a name="examples-ec2-key-pairs"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立金鑰對
<a name="create-a-key-pair"></a>

若要建立金鑰對，請使用包含金鑰名稱的 `CreateKeyPair` [CreateKeyPairRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_create_key_pair_request.html) 呼叫 EC2Client 函數。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/CreateKeyPairRequest.h>
#include <iostream>
#include <fstream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::CreateKeyPairRequest request;
    request.SetKeyName(keyPairName);

    Aws::EC2::Model::CreateKeyPairOutcome outcome = ec2Client.CreateKeyPair(request);
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to create key pair - "  << keyPairName << ". " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully created key pair named " <<
                  keyPairName << std::endl;
        if (!keyFilePath.empty()) {
            std::ofstream keyFile(keyFilePath.c_str());
            keyFile << outcome.GetResult().GetKeyMaterial();
            keyFile.close();
            std::cout << "Keys written to the file " <<
                      keyFilePath << std::endl;
        }

    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_key_pair.cpp)。

## 描述金鑰對
<a name="describe-key-pairs"></a>

若要列出您的金鑰對或取得相關資訊，請使用 [DescribeKeyPairsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_key_pairs_request.html) 呼叫 EC2Client 的 `DescribeKeyPairs`函數。

您將會收到 [DescribeKeyPairsResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_key_pairs_response.html)，您可以透過呼叫其函數來存取金鑰對的清單，該`GetKeyPairs`函數會傳回 [KeyPairInfo](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_key_pair_info.html) 物件的清單。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeKeyPairsRequest.h>
#include <aws/ec2/model/DescribeKeyPairsResponse.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeKeyPairsRequest request;

    Aws::EC2::Model::DescribeKeyPairsOutcome outcome = ec2Client.DescribeKeyPairs(request);
    if (outcome.IsSuccess()) {
        std::cout << std::left <<
                  std::setw(32) << "Name" <<
                  std::setw(64) << "Fingerprint" << std::endl;

        const std::vector<Aws::EC2::Model::KeyPairInfo> &key_pairs =
                outcome.GetResult().GetKeyPairs();
        for (const auto &key_pair: key_pairs) {
            std::cout << std::left <<
                      std::setw(32) << key_pair.GetKeyName() <<
                      std::setw(64) << key_pair.GetKeyFingerprint() << std::endl;
        }
    } else {
        std::cerr << "Failed to describe key pairs:" <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_key_pairs.cpp)。

## 刪除金鑰對
<a name="delete-a-key-pair"></a>

若要刪除金鑰對，請呼叫 EC2Client 的 `DeleteKeyPair`函數，將其傳遞 [DeleteKeyPairRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_delete_key_pair_request.html)，其中包含要刪除的金鑰對名稱。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DeleteKeyPairRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DeleteKeyPairRequest request;

    request.SetKeyName(keyPairName);
    const Aws::EC2::Model::DeleteKeyPairOutcome outcome = ec2Client.DeleteKeyPair(
            request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to delete key pair " << keyPairName <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted key pair named " << keyPairName <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/delete_key_pair.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《[Amazon EC2 使用者指南》中的 Amazon EC2 金鑰對](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) Amazon EC2 
+  Amazon EC2 API 參考中的 [CreateKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateKeyPair.html) 
+  Amazon EC2 API 參考中的 [DescribeKeyPairs](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeKeyPairs.html) 
+  Amazon EC2 API 參考中的 [DeleteKeyPair](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteKeyPair.html) 

# 在 Amazon EC2 中使用安全群組
<a name="examples-ec2-security-groups"></a>

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立安全群組
<a name="create-a-security-group"></a>

若要建立安全群組，請使用包含金鑰名稱的 `CreateSecurityGroup` [CreateSecurityGroupRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_create_security_group_request.html) 呼叫 EC2Client 函數。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/CreateSecurityGroupRequest.h>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);

    Aws::EC2::Model::CreateSecurityGroupRequest request;

    request.SetGroupName(groupName);
    request.SetDescription(description);
    request.SetVpcId(vpcID);

    const Aws::EC2::Model::CreateSecurityGroupOutcome outcome =
            ec2Client.CreateSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to create security group:" <<
                  outcome.GetError().GetMessage() << std::endl;
        return false;
    }

    std::cout << "Successfully created security group named " << groupName <<
              std::endl;
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_security_group.cpp)。

## 設定安全群組
<a name="configure-a-security-group"></a>

安全群組可以控制 Amazon EC2 執行個體的傳入 （傳入） 和傳出 （傳出） 流量。

若要將輸入規則新增至您的安全群組，請使用 EC2Client 的 `AuthorizeSecurityGroupIngress`函數，提供安全群組的名稱，以及您想要在 [AuthorizeSecurityGroupIngressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_authorize_security_group_ingress_request.html) 物件中為其指派的存取規則 ([IpPermission](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_ip_permission.html))。以下範例說明如何將 IP 許可新增至安全群組。

 **包括** 

```
#include <aws/ec2/model/AuthorizeSecurityGroupIngressRequest.h>
```

 **Code** 

```
    Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest;
    authorizeSecurityGroupIngressRequest.SetGroupId(groupID);
```

```
    Aws::String ingressIPRange = "203.0.113.0/24";  // Configure this for your allowed IP range.
    Aws::EC2::Model::IpRange ip_range;
    ip_range.SetCidrIp(ingressIPRange);

    Aws::EC2::Model::IpPermission permission1;
    permission1.SetIpProtocol("tcp");
    permission1.SetToPort(80);
    permission1.SetFromPort(80);
    permission1.AddIpRanges(ip_range);

    authorize_request.AddIpPermissions(permission1);

    Aws::EC2::Model::IpPermission permission2;
    permission2.SetIpProtocol("tcp");
    permission2.SetToPort(22);
    permission2.SetFromPort(22);
    permission2.AddIpRanges(ip_range);

    authorize_request.AddIpPermissions(permission2);
```

```
    Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeSecurityGroupIngressOutcome =
            ec2Client.AuthorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    if (authorizeSecurityGroupIngressOutcome.IsSuccess()) {
        std::cout << "Successfully authorized security group ingress." << std::endl;
    } else {
        std::cerr << "Error authorizing security group ingress: "
                  << authorizeSecurityGroupIngressOutcome.GetError().GetMessage() << std::endl;
    }
```

若要將輸出規則新增至安全群組，請將 [AuthorizeSecurityGroupEgressRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_authorize_security_group_egress_request.html) 中的類似資料提供給 EC2Client 的 `AuthorizeSecurityGroupEgress`函數。

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_security_group.cpp)。

## 描述安全群組
<a name="describe-security-groups"></a>

若要描述您的安全群組或取得相關資訊，請使用 [DescribeSecurityGroupsRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_security_groups_request.html) 呼叫 EC2Client 的 `DescribeSecurityGroups`函數。

您會在結果物件中收到 [DescribeSecurityGroupsResponse](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_describe_security_groups_response.html)，您可以透過呼叫其函數來存取安全群組清單，該`GetSecurityGroups`函數會傳回 [SecurityGroup](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_security_group.html) 物件清單。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DescribeSecurityGroupsRequest.h>
#include <aws/ec2/model/DescribeSecurityGroupsResponse.h>
#include <iomanip>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DescribeSecurityGroupsRequest request;

    if (!groupID.empty()) {
        request.AddGroupIds(groupID);
    }

    Aws::String nextToken;
    do {
        if (!nextToken.empty()) {
            request.SetNextToken(nextToken);
        }

        Aws::EC2::Model::DescribeSecurityGroupsOutcome outcome = ec2Client.DescribeSecurityGroups(request);
        if (outcome.IsSuccess()) {
            std::cout << std::left <<
                      std::setw(32) << "Name" <<
                      std::setw(30) << "GroupId" <<
                      std::setw(30) << "VpcId" <<
                      std::setw(64) << "Description" << std::endl;

            const std::vector<Aws::EC2::Model::SecurityGroup> &securityGroups =
                    outcome.GetResult().GetSecurityGroups();

            for (const auto &securityGroup: securityGroups) {
                std::cout << std::left <<
                          std::setw(32) << securityGroup.GetGroupName() <<
                          std::setw(30) << securityGroup.GetGroupId() <<
                          std::setw(30) << securityGroup.GetVpcId() <<
                          std::setw(64) << securityGroup.GetDescription() <<
                          std::endl;
            }
        } else {
            std::cerr << "Failed to describe security groups:" <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

        nextToken = outcome.GetResult().GetNextToken();
    } while (!nextToken.empty());
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/describe_security_groups.cpp)。

## 刪除安全群組
<a name="delete-a-security-group"></a>

若要刪除安全群組，請呼叫 EC2Client 的 `DeleteSecurityGroup`函數，並將其傳遞 [DeleteSecurityGroupRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-ec2/html/class_aws_1_1_e_c2_1_1_model_1_1_delete_security_group_request.html)，其中包含要刪除的安全群組 ID。

 **包括** 

```
#include <aws/ec2/EC2Client.h>
#include <aws/ec2/model/DeleteSecurityGroupRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::EC2::EC2Client ec2Client(clientConfiguration);
    Aws::EC2::Model::DeleteSecurityGroupRequest request;

    request.SetGroupId(securityGroupID);
    Aws::EC2::Model::DeleteSecurityGroupOutcome outcome = ec2Client.DeleteSecurityGroup(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Failed to delete security group " << securityGroupID <<
                  ":" << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted security group " << securityGroupID <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/delete_security_group.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  《[Amazon EC2 使用者指南》中的 Amazon EC2 安全群組](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html) Amazon EC2 
+  《Amazon EC2 使用者指南》中的[授權 Linux 執行個體的傳入流量](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html) 
+  Amazon EC2 API 參考中的 [CreateSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateSecurityGroup.html) 
+  Amazon EC2 API 參考中的 [DescribeSecurityGroups](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeSecurityGroups.html) 
+  Amazon EC2 API 參考中的 [DeleteSecurityGroup](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteSecurityGroup.html) 
+  Amazon EC2 API 參考中的 [AuthorizeSecurityGroupIngress](https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_AuthorizeSecurityGroupIngress.html) 

# 使用 的 Amazon S3 程式碼範例 適用於 C\$1\$1 的 AWS SDK
<a name="examples-s3"></a>

[Amazon S3](https://aws.amazon.com/s3) 是物件儲存體，用於從任何地方存放和擷取任意數量的資料。提供多個類別 適用於 C\$1\$1 的 AWS SDK 以與 Amazon S3 連接。

**注意**  
本指南僅提供示範特定技術所需的程式碼，但[完整的範例程式碼可在 GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。在 GitHub 上，您可以下載單一來源檔案，也可以在本機複製儲存庫，以取得、建置和執行所有範例。
+ [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_s3_client.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_s3_client.html) 類別 

  `S3Client` 程式庫是功能完整的 Amazon S3 介面。

  此集中`list_buckets_disabling_dns_cache.cpp`的範例專為在 Linux/Mac 上使用 CURL 而設計 （雖然可以修改為在 Windows 上使用）。如果您在 Windows 上，請在建置專案`list_buckets_disabling_dns_cache.cpp`之前刪除 檔案，因為它依賴 Linux 的 curl HttpClient。

  使用 的範例程式碼`S3Client`位於 Github 的 [`s3` 資料夾中](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3)。如需此範例集示範的完整函數清單，請參閱 Github 上的[讀我](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/README.md)檔案。

  本指南中會詳細說明`s3`範例集的部分：
  + [建立、列出和刪除儲存貯體](examples-s3-buckets.md)
  + [可對物件執行的操作](examples-s3-objects.md) – 上傳和下載資料物件
  + [管理 Amazon S3 存取許可](examples-s3-access-permissions.md)
  + [使用儲存貯體政策管理對 Amazon S3 儲存貯體的存取](examples-s3-bucket-policies.md)
  + [將 Amazon S3 儲存貯體設定為網站](examples-s3-website-configuration.md)
+ [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3-crt/html/class_aws_1_1_s3_crt_1_1_s3_crt_client.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3-crt/html/class_aws_1_1_s3_crt_1_1_s3_crt_client.html) 類別 

  `S3CrtClient` 已在 SDK 的 1.9 版中新增 。 為 Amazon S3 GET （下載） 和 PUT （上傳） 操作`S3CrtClient`提供高輸送量。在 AWS 通用執行期 (CRT) 程式庫的頂端`S3CrtClient`實作 。

  使用 的範例程式碼`S3CrtClient`位於 Github 的 [`s3-crt` 資料夾中](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3-crt)。如需此範例集示範的完整函數清單，請參閱 Github 上的[讀我](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3-crt/README.md)檔案。
  + [使用 `S3CrtClient`進行 Amazon S3 操作](examples-s3-crt.md)
+ [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-transfer/html/class_aws_1_1_transfer_1_1_transfer_manager.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-transfer/html/class_aws_1_1_transfer_1_1_transfer_manager.html) 類別 

  `TransferManager` 是一種全受管服務，可透過檔案傳輸協定 (FTP)、透過 SSL 的檔案傳輸協定 (FTPS) 或 Secure Shell (SSH) 檔案傳輸協定 (SFTP) 直接傳入和傳出 Amazon S3。

  使用 的範例程式碼`TransferManager`位於 Github 的 [`transfer-manager` 資料夾中](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/transfer-manager)。如需此範例集示範的完整函數清單，請參閱 Github 上的[讀我](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/transfer-manager/README.md)檔案。
  + [將 TransferManager 用於 Amazon S3 操作](examples-s3-transfermanager.md)

# 建立、列出和刪除儲存貯體
<a name="examples-s3-buckets"></a>

Amazon Simple Storage Service (Amazon S3) 中的每個*物件*或檔案都包含在代表物件資料夾的*儲存貯*體中。每個儲存貯體都有一個全域唯一的名稱 AWS。如需詳細資訊，請參閱《[Amazon Simple Storage Service 使用者指南》中的使用 Amazon S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html)體。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如 中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來發出請求的使用者設定檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 列出儲存貯體
<a name="list-buckets"></a>

若要執行`list_buckets`範例，請在命令提示字元中，導覽至建置系統建立建置可執行檔的資料夾。像 一樣執行可執行檔 `run_list_buckets`（您的完整可執行檔名會根據您的作業系統而有所不同）。如果您有任何儲存貯體，輸出會列出您帳戶的儲存貯體，或者如果您沒有任何儲存貯體，則會顯示空白清單。

在 中`list_buckets.cpp`，有兩種方法。
+ `main()` 呼叫 `ListBuckets()`。
+ `ListBuckets()` 使用 SDK 查詢您的儲存貯體。

`S3Client` 物件會呼叫 SDK 的 `ListBuckets()`方法。如果成功， 方法會傳回包含`ListBucketOutcome`物件的`ListBucketResult`物件。`ListBucketResult` 物件會呼叫 `GetBuckets()`方法，以取得包含您帳戶中每個 Amazon S3 儲存貯體相關資訊的`Bucket`物件清單。

 **Code** 

```
bool AwsDoc::S3::listBuckets(const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    auto outcome = client.ListBuckets();

    bool result = true;
    if (!outcome.IsSuccess()) {
        std::cerr << "Failed with error: " << outcome.GetError() << std::endl;
        result = false;
    } else {
        std::cout << "Found " << outcome.GetResult().GetBuckets().size() << " buckets\n";
        for (auto &&b: outcome.GetResult().GetBuckets()) {
            std::cout << b.GetName() << std::endl;
        }
    }

    return result;
}
```

請參閱 Github 上的完整 [list\$1buckets 範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/list_buckets.cpp)。

## 建立 儲存貯體
<a name="create-bucket"></a>



若要執行`create_bucket`範例，請在命令提示字元中，導覽至建置系統建立建置可執行檔的資料夾。像 一樣執行可執行檔 `run_create_bucket`（您的完整可執行檔名會根據您的作業系統而有所不同）。程式碼會在您的帳戶下建立空儲存貯體，然後顯示請求的成功或失敗。

在 中`create_bucket.cpp`，有兩種方法。
+ `main()` 呼叫 `CreateBucket()`。在 中`main()`，您需要使用 將 AWS 區域 變更為帳戶的 區域`enum`。您可以登入 並找到右上角的區域[AWS 管理主控台](https://console.aws.amazon.com/)，以檢視您 帳戶的 區域。
+ `CreateBucket()` 使用 SDK 來建立儲存貯體。



`S3Client` 物件會呼叫 SDK 的 `CreateBucket()`方法，`CreateBucketRequest`以儲存貯體的名稱傳入 。根據預設，儲存貯體會在 *us-east-1* （維吉尼亞北部） 區域中建立。如果您的區域不是 *us-east-1*，則程式碼會設定儲存貯體限制，以確保儲存貯體在您的區域中建立。

 **Code** 

```
bool AwsDoc::S3::createBucket(const Aws::String &bucketName,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::CreateBucketRequest request;
    request.SetBucket(bucketName);

    if (clientConfig.region != "us-east-1") {
        Aws::S3::Model::CreateBucketConfiguration createBucketConfig;
        createBucketConfig.SetLocationConstraint(
                Aws::S3::Model::BucketLocationConstraintMapper::GetBucketLocationConstraintForName(
                        clientConfig.region));
        request.SetCreateBucketConfiguration(createBucketConfig);
    }

    Aws::S3::Model::CreateBucketOutcome outcome = client.CreateBucket(request);
    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: createBucket: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Created bucket " << bucketName <<
                  " in the specified AWS Region." << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 Github 上完整的 [create\$1buckets 範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/create_bucket.cpp)。

## 刪除 儲存貯體
<a name="delete-bucket"></a>



若要執行`delete_bucket`範例，請在命令提示字元中，導覽至建置系統建立建置可執行檔的資料夾。像 一樣執行可執行檔 `run_delete_bucket`（您的完整可執行檔名會根據您的作業系統而有所不同）。程式碼會刪除您帳戶中指定的儲存貯體，然後顯示請求的成功或失敗。

在 `delete_bucket.cpp`中有兩種方法。
+ `main()` 呼叫 `DeleteBucket()`。在 中`main()`，您需要使用 將 AWS 區域 變更為帳戶的 區域`enum`。您也需要將 `bucket_name` 變更為要刪除的儲存貯體名稱。
+ `DeleteBucket()` 使用 SDK 刪除儲存貯體。



`S3Client` 物件使用 SDK 的 `DeleteBucket()`方法，傳入具有要刪除之儲存貯體名稱的`DeleteBucketRequest`物件。儲存貯體必須為空，才能成功。

 **Code**

```
bool AwsDoc::S3::deleteBucket(const Aws::String &bucketName,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {

    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::DeleteBucketRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketOutcome outcome =
            client.DeleteBucket(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: deleteBucket: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "The bucket was deleted" << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 Github 上完整的 [delete\$1bucket 範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_bucket.cpp)。

# 可對物件執行的操作
<a name="examples-s3-objects"></a>

Amazon S3 物件代表*檔案*，這是資料集合。每個物件都必須位於儲存[貯](examples-s3-buckets.md)體中。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 將檔案上傳至儲存貯體
<a name="upload-object"></a>

使用 `S3Client` 物件`PutObject`函數，提供儲存貯體名稱、金鑰名稱和要上傳的檔案。 `Aws::FStream` 用於將本機檔案的內容上傳至儲存貯體。儲存貯體必須存在，否則會產生錯誤。

如需非同步上傳物件的範例，請參閱 [使用 進行非同步程式設計 適用於 C\$1\$1 的 AWS SDK](async-methods.md)

 **Code** 

```
bool AwsDoc::S3::putObject(const Aws::String &bucketName,
                           const Aws::String &fileName,
                           const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    //We are using the name of the file as the key for the object in the bucket.
    //However, this is just a string and can be set according to your retrieval needs.
    request.SetKey(fileName);

    std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::FStream>("SampleAllocationTag",
                                          fileName.c_str(),
                                          std::ios_base::in | std::ios_base::binary);

    if (!*inputData) {
        std::cerr << "Error unable to read file " << fileName << std::endl;
        return false;
    }

    request.SetBody(inputData);

    Aws::S3::Model::PutObjectOutcome outcome =
            s3Client.PutObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putObject: " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Added object '" << fileName << "' to bucket '"
                  << bucketName << "'.";
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_object.cpp)。

## 將字串上傳至儲存貯體
<a name="upload-object-string"></a>

使用 `S3Client` 物件`PutObject`函數，提供儲存貯體名稱、金鑰名稱和要上傳的檔案。儲存貯體必須存在，否則會產生錯誤。此範例使用 `Aws::StringStream`將記憶體內字串資料物件直接上傳至儲存貯體，與上一個範例不同。

如需非同步上傳物件的範例，請參閱 [使用 進行非同步程式設計 適用於 C\$1\$1 的 AWS SDK](async-methods.md)

 **Code** 

```
bool AwsDoc::S3::putObjectBuffer(const Aws::String &bucketName,
                                 const Aws::String &objectName,
                                 const std::string &objectContent,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::PutObjectRequest request;
    request.SetBucket(bucketName);
    request.SetKey(objectName);

    const std::shared_ptr<Aws::IOStream> inputData =
            Aws::MakeShared<Aws::StringStream>("");
    *inputData << objectContent.c_str();

    request.SetBody(inputData);

    Aws::S3::Model::PutObjectOutcome outcome = s3Client.PutObject(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putObjectBuffer: " <<
                  outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Success: Object '" << objectName << "' with content '"
                  << objectContent << "' uploaded to bucket '" << bucketName << "'.";
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_object_buffer.cpp)。

## 列出物件
<a name="list-objects"></a>

若要取得儲存貯體中的物件清單，請使用 `S3Client` 物件`ListObjects`函數。提供您使用儲存貯體名稱設定的 `ListObjectsRequest` ，以列出 的內容。

`ListObjects` 函數會傳回`ListObjectsOutcome`物件，您可以用來取得`Object`執行個體形式的物件清單。

 **Code** 

```
bool AwsDoc::S3::listObjects(const Aws::String &bucketName,
                             Aws::Vector<Aws::String> &keysResult,
                             const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::ListObjectsV2Request request;
    request.WithBucket(bucketName);

    Aws::String continuationToken; // Used for pagination.
    Aws::Vector<Aws::S3::Model::Object> allObjects;

    do {
        if (!continuationToken.empty()) {
            request.SetContinuationToken(continuationToken);
        }

        auto outcome = s3Client.ListObjectsV2(request);

        if (!outcome.IsSuccess()) {
            std::cerr << "Error: listObjects: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        } else {
            Aws::Vector<Aws::S3::Model::Object> objects =
                    outcome.GetResult().GetContents();

            allObjects.insert(allObjects.end(), objects.begin(), objects.end());
            continuationToken = outcome.GetResult().GetNextContinuationToken();
        }
    } while (!continuationToken.empty());

    std::cout << allObjects.size() << " object(s) found:" << std::endl;

    for (const auto &object: allObjects) {
        std::cout << "  " << object.GetKey() << std::endl;
        keysResult.push_back(object.GetKey());
    }

    return true;
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/list_objects.cpp)。

## 下載物件
<a name="download-object"></a>

使用 `S3Client` 物件`GetObject`函數，傳遞`GetObjectRequest`您使用儲存貯體名稱和要下載的物件金鑰設定的 。 `GetObject`會傳回包含 [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_object_result.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_object_result.html)和 的[https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/namespace_aws_1_1_s3_1_1_model.html#a6e16a7b25e8c7547934968a538a15272](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/namespace_aws_1_1_s3_1_1_model.html#a6e16a7b25e8c7547934968a538a15272)物件[https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_s3_error.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_s3_error.html)。 `GetObjectResult` 可用來存取 S3 物件的資料。

下列範例會從 Amazon S3 下載物件。物件內容存放在本機變數中，內容的第一行會輸出到主控台。

 **Code** 

```
bool AwsDoc::S3::getObject(const Aws::String &objectKey,
                           const Aws::String &fromBucket,
                           const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::GetObjectRequest request;
    request.SetBucket(fromBucket);
    request.SetKey(objectKey);

    Aws::S3::Model::GetObjectOutcome outcome =
            client.GetObject(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully retrieved '" << objectKey << "' from '"
                  << fromBucket << "'." << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_object.cpp)。

## 刪除物件
<a name="delete-object"></a>

使用`S3Client`物件的 `DeleteObject`函數，傳遞`DeleteObjectRequest`您使用儲存貯體名稱和要下載的物件所設定的 。*指定的儲存貯體和物件金鑰必須存在，否則會產生錯誤*。

 **Code** 

```
bool AwsDoc::S3::deleteObject(const Aws::String &objectKey,
                              const Aws::String &fromBucket,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::DeleteObjectRequest request;

    request.WithKey(objectKey)
            .WithBucket(fromBucket);

    Aws::S3::Model::DeleteObjectOutcome outcome =
            client.DeleteObject(request);

    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: deleteObject: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully deleted the object." << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_object.cpp)。

# 管理 Amazon S3 存取許可
<a name="examples-s3-access-permissions"></a>

Amazon S3 儲存貯體或物件的存取許可是在存取控制清單 (ACL) 中定義。ACL 會指定儲存貯體/物件的擁有者，以及授予清單。每個授予都會指定使用者 （或承授者） 和使用者存取儲存貯體/物件的許可，例如讀取或寫入存取。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 管理物件的存取控制清單
<a name="manage-an-object-s-access-control-list"></a>

您可以透過呼叫`S3Client`方法 來擷取物件的存取控制清單`GetObjectAcl`。方法接受物件的名稱及其儲存貯體。傳回值包含 ACL 的 `Owner`和 清單`Grants`。

```
bool AwsDoc::S3::getObjectAcl(const Aws::String &bucketName,
                              const Aws::String &objectKey,
                              const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetObjectAclRequest request;
    request.SetBucket(bucketName);
    request.SetKey(objectKey);

    Aws::S3::Model::GetObjectAclOutcome outcome =
            s3Client.GetObjectAcl(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getObjectAcl: "
                  << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        Aws::Vector<Aws::S3::Model::Grant> grants =
                outcome.GetResult().GetGrants();

        for (auto it = grants.begin(); it != grants.end(); it++) {
            std::cout << "For object " << objectKey << ": "
                      << std::endl << std::endl;

            Aws::S3::Model::Grant grant = *it;
            Aws::S3::Model::Grantee grantee = grant.GetGrantee();

            if (grantee.TypeHasBeenSet()) {
                std::cout << "Type:          "
                          << getGranteeTypeString(grantee.GetType()) << std::endl;
            }

            if (grantee.DisplayNameHasBeenSet()) {
                std::cout << "Display name:  "
                          << grantee.GetDisplayName() << std::endl;
            }

            if (grantee.EmailAddressHasBeenSet()) {
                std::cout << "Email address: "
                          << grantee.GetEmailAddress() << std::endl;
            }

            if (grantee.IDHasBeenSet()) {
                std::cout << "ID:            "
                          << grantee.GetID() << std::endl;
            }

            if (grantee.URIHasBeenSet()) {
                std::cout << "URI:           "
                          << grantee.GetURI() << std::endl;
            }

            std::cout << "Permission:    " <<
                      getPermissionString(grant.GetPermission()) <<
                      std::endl << std::endl;
        }
    }

    return outcome.IsSuccess();
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param type: Type enumeration.
 \return String: Human-readable string
*/
Aws::String getGranteeTypeString(const Aws::S3::Model::Type &type) {
    switch (type) {
        case Aws::S3::Model::Type::AmazonCustomerByEmail:
            return "Email address of an AWS account";
        case Aws::S3::Model::Type::CanonicalUser:
            return "Canonical user ID of an AWS account";
        case Aws::S3::Model::Type::Group:
            return "Predefined Amazon S3 group";
        case Aws::S3::Model::Type::NOT_SET:
            return "Not set";
        default:
            return "Type unknown";
    }
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param permission: Permission enumeration.
 \return String: Human-readable string
*/
Aws::String getPermissionString(const Aws::S3::Model::Permission &permission) {
    switch (permission) {
        case Aws::S3::Model::Permission::FULL_CONTROL:
            return "Can read this object's data and its metadata, "
                   "and read/write this object's permissions";
        case Aws::S3::Model::Permission::NOT_SET:
            return "Permission not set";
        case Aws::S3::Model::Permission::READ:
            return "Can read this object's data and its metadata";
        case Aws::S3::Model::Permission::READ_ACP:
            return "Can read this object's permissions";
            // case Aws::S3::Model::Permission::WRITE // Not applicable.
        case Aws::S3::Model::Permission::WRITE_ACP:
            return "Can write this object's permissions";
        default:
            return "Permission unknown";
    }
}
```

您可以透過建立新的 ACL 或變更目前 ACL 中指定的授予來修改 ACL。更新的 ACL 透過將其傳遞至 `PutObjectAcl`方法，成為新的目前 ACL。

下列程式碼使用 擷取的 ACL，`GetObjectAcl`並為其新增新的授權。使用者或承授者會獲得物件的 READ 許可。修改後的 ACL 會傳遞至 `PutObjectAcl`，使其成為新的目前 ACL。

```
bool AwsDoc::S3::putObjectAcl(const Aws::String &bucketName, const Aws::String &objectKey, const Aws::String &ownerID,
                              const Aws::String &granteePermission, const Aws::String &granteeType,
                              const Aws::String &granteeID, const Aws::String &granteeEmailAddress,
                              const Aws::String &granteeURI, const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::Owner owner;
    owner.SetID(ownerID);

    Aws::S3::Model::Grantee grantee;
    grantee.SetType(setGranteeType(granteeType));

    if (!granteeEmailAddress.empty()) {
        grantee.SetEmailAddress(granteeEmailAddress);
    }

    if (!granteeID.empty()) {
        grantee.SetID(granteeID);
    }

    if (!granteeURI.empty()) {
        grantee.SetURI(granteeURI);
    }

    Aws::S3::Model::Grant grant;
    grant.SetGrantee(grantee);
    grant.SetPermission(setGranteePermission(granteePermission));

    Aws::Vector<Aws::S3::Model::Grant> grants;
    grants.push_back(grant);

    Aws::S3::Model::AccessControlPolicy acp;
    acp.SetOwner(owner);
    acp.SetGrants(grants);

    Aws::S3::Model::PutObjectAclRequest request;
    request.SetAccessControlPolicy(acp);
    request.SetBucket(bucketName);
    request.SetKey(objectKey);

    Aws::S3::Model::PutObjectAclOutcome outcome =
            s3Client.PutObjectAcl(request);

    if (!outcome.IsSuccess()) {
        auto error = outcome.GetError();
        std::cerr << "Error: putObjectAcl: " << error.GetExceptionName()
                  << " - " << error.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully added an ACL to the object '" << objectKey
                  << "' in the bucket '" << bucketName << "'." << std::endl;
    }

    return outcome.IsSuccess();
}

//! Routine which converts a human-readable string to a built-in type enumeration.
/*!
 \param access: Human readable string.
 \return Permission: Permission enumeration.
*/
Aws::S3::Model::Permission setGranteePermission(const Aws::String &access) {
    if (access == "FULL_CONTROL")
        return Aws::S3::Model::Permission::FULL_CONTROL;
    if (access == "WRITE")
        return Aws::S3::Model::Permission::WRITE;
    if (access == "READ")
        return Aws::S3::Model::Permission::READ;
    if (access == "WRITE_ACP")
        return Aws::S3::Model::Permission::WRITE_ACP;
    if (access == "READ_ACP")
        return Aws::S3::Model::Permission::READ_ACP;
    return Aws::S3::Model::Permission::NOT_SET;
}

//! Routine which converts a human-readable string to a built-in type enumeration.
/*!
 \param type: Human readable string.
 \return Type: Type enumeration.
*/
Aws::S3::Model::Type setGranteeType(const Aws::String &type) {
    if (type == "Amazon customer by email")
        return Aws::S3::Model::Type::AmazonCustomerByEmail;
    if (type == "Canonical user")
        return Aws::S3::Model::Type::CanonicalUser;
    if (type == "Group")
        return Aws::S3::Model::Type::Group;
    return Aws::S3::Model::Type::NOT_SET;
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_put_object_acl.cpp)。

## 管理儲存貯體的存取控制清單
<a name="manage-a-bucket-s-access-control-list"></a>

在大多數情況下，設定儲存貯體存取許可的偏好方法是定義儲存貯體政策。不過，儲存貯體也支援希望使用它們的使用者的存取控制清單。

儲存貯體存取控制清單的管理與用於物件的存取控制清單相同。`GetBucketAcl` 方法會擷取儲存貯體目前的 ACL，並將新的 ACL `PutBucketAcl`套用至儲存貯體。

下列程式碼示範取得和設定儲存貯體 ACL。

```
//! Routine which demonstrates setting the ACL for an S3 bucket.
/*!
  \param bucketName: Name of a bucket.
  \param ownerID: The canonical ID of the bucket owner.
   See https://docs.aws.amazon.com/AmazonS3/latest/userguide/finding-canonical-user-id.html for more information.
  \param granteePermission: The access level to enable for the grantee.
  \param granteeType: The type of grantee.
  \param granteeID: The canonical ID of the grantee.
  \param granteeEmailAddress: The email address associated with the grantee's AWS account.
  \param granteeURI: The URI of a built-in access group.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/

bool AwsDoc::S3::getPutBucketAcl(const Aws::String &bucketName,
                                 const Aws::String &ownerID,
                                 const Aws::String &granteePermission,
                                 const Aws::String &granteeType,
                                 const Aws::String &granteeID,
                                 const Aws::String &granteeEmailAddress,
                                 const Aws::String &granteeURI,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    bool result = ::putBucketAcl(bucketName, ownerID, granteePermission, granteeType,
                                 granteeID,
                                 granteeEmailAddress,
                                 granteeURI,
                                 clientConfig);
    if (result) {
        result = ::getBucketAcl(bucketName, clientConfig);
    }

    return result;
}

//! Routine which demonstrates setting the ACL for an S3 bucket.
/*!
  \param bucketName: Name of from bucket.
  \param ownerID: The canonical ID of the bucket owner.
   See https://docs.aws.amazon.com/AmazonS3/latest/userguide/finding-canonical-user-id.html for more information.
  \param granteePermission: The access level to enable for the grantee.
  \param granteeType: The type of grantee.
  \param granteeID: The canonical ID of the grantee.
  \param granteeEmailAddress: The email address associated with the grantee's AWS account.
  \param granteeURI: The URI of a built-in access group.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/

bool putBucketAcl(const Aws::String &bucketName,
                  const Aws::String &ownerID,
                  const Aws::String &granteePermission,
                  const Aws::String &granteeType,
                  const Aws::String &granteeID,
                  const Aws::String &granteeEmailAddress,
                  const Aws::String &granteeURI,
                  const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::Owner owner;
    owner.SetID(ownerID);

    Aws::S3::Model::Grantee grantee;
    grantee.SetType(setGranteeType(granteeType));

    if (!granteeEmailAddress.empty()) {
        grantee.SetEmailAddress(granteeEmailAddress);
    }

    if (!granteeID.empty()) {
        grantee.SetID(granteeID);
    }

    if (!granteeURI.empty()) {
        grantee.SetURI(granteeURI);
    }

    Aws::S3::Model::Grant grant;
    grant.SetGrantee(grantee);
    grant.SetPermission(setGranteePermission(granteePermission));

    Aws::Vector<Aws::S3::Model::Grant> grants;
    grants.push_back(grant);

    Aws::S3::Model::AccessControlPolicy acp;
    acp.SetOwner(owner);
    acp.SetGrants(grants);

    Aws::S3::Model::PutBucketAclRequest request;
    request.SetAccessControlPolicy(acp);
    request.SetBucket(bucketName);

    Aws::S3::Model::PutBucketAclOutcome outcome =
            s3Client.PutBucketAcl(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &error = outcome.GetError();

        std::cerr << "Error: putBucketAcl: " << error.GetExceptionName()
                  << " - " << error.GetMessage() << std::endl;
    } else {
        std::cout << "Successfully added an ACL to the bucket '" << bucketName
                  << "'." << std::endl;
    }

    return outcome.IsSuccess();
}

//! Routine which demonstrates getting the ACL for an S3 bucket.
/*!
  \param bucketName: Name of the s3 bucket.
  \param clientConfig: Aws client configuration.
  \return bool: Function succeeded.
*/
bool getBucketAcl(const Aws::String &bucketName,
                  const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetBucketAclRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::GetBucketAclOutcome outcome =
            s3Client.GetBucketAcl(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getBucketAcl: "
                  << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        const Aws::Vector<Aws::S3::Model::Grant> &grants =
                outcome.GetResult().GetGrants();

        for (const Aws::S3::Model::Grant &grant: grants) {
            const Aws::S3::Model::Grantee &grantee = grant.GetGrantee();

            std::cout << "For bucket " << bucketName << ": "
                      << std::endl << std::endl;

            if (grantee.TypeHasBeenSet()) {
                std::cout << "Type:          "
                          << getGranteeTypeString(grantee.GetType()) << std::endl;
            }

            if (grantee.DisplayNameHasBeenSet()) {
                std::cout << "Display name:  "
                          << grantee.GetDisplayName() << std::endl;
            }

            if (grantee.EmailAddressHasBeenSet()) {
                std::cout << "Email address: "
                          << grantee.GetEmailAddress() << std::endl;
            }

            if (grantee.IDHasBeenSet()) {
                std::cout << "ID:            "
                          << grantee.GetID() << std::endl;
            }

            if (grantee.URIHasBeenSet()) {
                std::cout << "URI:           "
                          << grantee.GetURI() << std::endl;
            }

            std::cout << "Permission:    " <<
                      getPermissionString(grant.GetPermission()) <<
                      std::endl << std::endl;
        }
    }

    return outcome.IsSuccess();
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param permission: Permission enumeration.
 \return String: Human-readable string.
*/

Aws::String getPermissionString(const Aws::S3::Model::Permission &permission) {
    switch (permission) {
        case Aws::S3::Model::Permission::FULL_CONTROL:
            return "Can list objects in this bucket, create/overwrite/delete "
                   "objects in this bucket, and read/write this "
                   "bucket's permissions";
        case Aws::S3::Model::Permission::NOT_SET:
            return "Permission not set";
        case Aws::S3::Model::Permission::READ:
            return "Can list objects in this bucket";
        case Aws::S3::Model::Permission::READ_ACP:
            return "Can read this bucket's permissions";
        case Aws::S3::Model::Permission::WRITE:
            return "Can create, overwrite, and delete objects in this bucket";
        case Aws::S3::Model::Permission::WRITE_ACP:
            return "Can write this bucket's permissions";
        default:
            return "Permission unknown";
    }
}

//! Routine which converts a human-readable string to a built-in type enumeration
/*!
 \param access: Human readable string.
 \return Permission: Permission enumeration.
*/
Aws::S3::Model::Permission setGranteePermission(const Aws::String &access) {
    if (access == "FULL_CONTROL")
        return Aws::S3::Model::Permission::FULL_CONTROL;
    if (access == "WRITE")
        return Aws::S3::Model::Permission::WRITE;
    if (access == "READ")
        return Aws::S3::Model::Permission::READ;
    if (access == "WRITE_ACP")
        return Aws::S3::Model::Permission::WRITE_ACP;
    if (access == "READ_ACP")
        return Aws::S3::Model::Permission::READ_ACP;
    return Aws::S3::Model::Permission::NOT_SET;
}

//! Routine which converts a built-in type enumeration to a human-readable string.
/*!
 \param type: Type enumeration.
 \return bool: Human-readable string.
*/
Aws::String getGranteeTypeString(const Aws::S3::Model::Type &type) {
    switch (type) {
        case Aws::S3::Model::Type::AmazonCustomerByEmail:
            return "Email address of an AWS account";
        case Aws::S3::Model::Type::CanonicalUser:
            return "Canonical user ID of an AWS account";
        case Aws::S3::Model::Type::Group:
            return "Predefined Amazon S3 group";
        case Aws::S3::Model::Type::NOT_SET:
            return "Not set";
        default:
            return "Type unknown";
    }
}

Aws::S3::Model::Type setGranteeType(const Aws::String &type) {
    if (type == "Amazon customer by email")
        return Aws::S3::Model::Type::AmazonCustomerByEmail;
    if (type == "Canonical user")
        return Aws::S3::Model::Type::CanonicalUser;
    if (type == "Group")
        return Aws::S3::Model::Type::Group;
    return Aws::S3::Model::Type::NOT_SET;
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_put_bucket_acl.cpp)。

# 使用儲存貯體政策管理對 Amazon S3 儲存貯體的存取
<a name="examples-s3-bucket-policies"></a>

您可以設定、取得或刪除儲存*貯體政策*，以管理對 Amazon S3 儲存貯體的存取。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 設定儲存貯體政策
<a name="set-s3-bucket-policy"></a>

您可以呼叫 `S3Client`的 `PutBucketPolicy`函數，並在 [PutBucketPolicyRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_put_bucket_policy_request.html) 中提供儲存貯體名稱和政策的 JSON 表示法，來設定特定 S3 儲存貯體的儲存貯體政策。

 **Code** 

```
//! Build a policy JSON string.
/*!
  \param userArn: Aws user Amazon Resource Name (ARN).
      For more information, see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns.
  \param bucketName: Name of a bucket.
  \return String: Policy as JSON string.
*/

Aws::String getPolicyString(const Aws::String &userArn,
                            const Aws::String &bucketName) {
    return
            "{\n"
            "   \"Version\":\"2012-10-17\",\n"
            "   \"Statement\":[\n"
            "       {\n"
            "           \"Sid\": \"1\",\n"
            "           \"Effect\": \"Allow\",\n"
            "           \"Principal\": {\n"
            "               \"AWS\": \""
            + userArn +
            "\"\n""           },\n"
            "           \"Action\": [ \"s3:getObject\" ],\n"
            "           \"Resource\": [ \"arn:aws:s3:::"
            + bucketName +
            "/*\" ]\n"
            "       }\n"
            "   ]\n"
            "}";
}
```

```
bool AwsDoc::S3::putBucketPolicy(const Aws::String &bucketName,
                                 const Aws::String &policyBody,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    std::shared_ptr<Aws::StringStream> request_body =
            Aws::MakeShared<Aws::StringStream>("");
    *request_body << policyBody;

    Aws::S3::Model::PutBucketPolicyRequest request;
    request.SetBucket(bucketName);
    request.SetBody(request_body);

    Aws::S3::Model::PutBucketPolicyOutcome outcome =
            s3Client.PutBucketPolicy(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: putBucketPolicy: "
                  << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Set the following policy body for the bucket '" <<
                  bucketName << "':" << std::endl << std::endl;
        std::cout << policyBody << std::endl;
    }

    return outcome.IsSuccess();
}
```

**注意**  
[Aws：：Utils：：Json：：JsonValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-core/html/class_aws_1_1_utils_1_1_json_1_1_json_value.html) 公用程式類別可用來協助您建構有效的 JSON 物件以傳遞至 `PutBucketPolicy`。

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_bucket_policy.cpp)。

## 取得儲存貯體政策
<a name="get-s3-bucket-policy"></a>

若要擷取 Amazon S3 儲存貯體的政策，請呼叫 `S3Client`的 `GetBucketPolicy`函數，並在 [GetBucketPolicyRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_bucket_policy_request.html) 中傳遞儲存貯體的名稱。

 **Code** 

```
bool AwsDoc::S3::getBucketPolicy(const Aws::String &bucketName,
                                 const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetBucketPolicyRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::GetBucketPolicyOutcome outcome =
            s3Client.GetBucketPolicy(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: getBucketPolicy: "
                  << err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        Aws::StringStream policy_stream;
        Aws::String line;

        outcome.GetResult().GetPolicy() >> line;
        policy_stream << line;

        std::cout << "Retrieve the policy for bucket '" << bucketName << "':\n\n" <<
                  policy_stream.str() << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_bucket_policy.cpp)。

## 刪除儲存貯體政策
<a name="delete-s3-bucket-policy"></a>

若要刪除儲存貯體政策，請呼叫 `S3Client`的 `DeleteBucketPolicy`函數，在 [DeleteBucketPolicyRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_delete_bucket_policy_request.html) 中提供儲存貯體名稱。

 **Code** 

```
bool AwsDoc::S3::deleteBucketPolicy(const Aws::String &bucketName,
                                    const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::DeleteBucketPolicyRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketPolicyOutcome outcome = client.DeleteBucketPolicy(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();
        std::cerr << "Error: deleteBucketPolicy: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Policy was deleted from the bucket." << std::endl;
    }

    return outcome.IsSuccess();
}
```

即使儲存貯體還沒有政策，此函數也會成功。如果您指定不存在的儲存貯體名稱，或如果您無法存取儲存貯體，`AmazonServiceException`則會擲出 。

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_bucket_policy.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  Amazon Simple Storage Service API 參考中的 [PutBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/PutBucketPolicy.html) 
+  Amazon Simple Storage Service API 參考中的 [GetBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/GetBucketPolicy.html) 
+  Amazon Simple Storage Service API 參考中的 [DeleteBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/DeleteBucketPolicy.html) 
+  《Amazon Simple Storage Service 使用者指南》中的[存取政策語言概觀](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-policy-language-overview.html) 
+  《Amazon Simple Storage Service 使用者指南》中的[儲存貯體政策範例](https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html) 

# 將 Amazon S3 儲存貯體設定為網站
<a name="examples-s3-website-configuration"></a>

您可以設定 Amazon S3 儲存貯體做為網站運作。若要這樣做，您需要設定其網站組態。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 設定儲存貯體的網站組態
<a name="set-a-bucket-s-website-configuration"></a>

若要設定 Amazon S3 儲存貯體的網站組態，請使用 [WebsiteConfiguration](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_website_configuration.html) 物件中提供的 [PutBucketWebsiteRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_put_bucket_website_request.html) 物件來呼叫 `S3Client`的 `PutBucketWebsite`函數，其中包含儲存貯體名稱及其網站組態。

*需要*設定索引文件；所有其他參數都是選用的。

 **Code** 

```
bool AwsDoc::S3::putWebsiteConfig(const Aws::String &bucketName,
                                  const Aws::String &indexPage, const Aws::String &errorPage,
                                  const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);

    Aws::S3::Model::IndexDocument indexDocument;
    indexDocument.SetSuffix(indexPage);

    Aws::S3::Model::ErrorDocument errorDocument;
    errorDocument.SetKey(errorPage);

    Aws::S3::Model::WebsiteConfiguration websiteConfiguration;
    websiteConfiguration.SetIndexDocument(indexDocument);
    websiteConfiguration.SetErrorDocument(errorDocument);

    Aws::S3::Model::PutBucketWebsiteRequest request;
    request.SetBucket(bucketName);
    request.SetWebsiteConfiguration(websiteConfiguration);

    Aws::S3::Model::PutBucketWebsiteOutcome outcome =
            client.PutBucketWebsite(request);

    if (!outcome.IsSuccess()) {
        std::cerr << "Error: PutBucketWebsite: "
                  << outcome.GetError().GetMessage() << std::endl;
    } else {
        std::cout << "Success: Set website configuration for bucket '"
                  << bucketName << "'." << std::endl;
    }

    return outcome.IsSuccess();
}
```

**注意**  
設定網站組態不會修改儲存貯體的存取許可。若要在 Web 上顯示您的檔案，您還需要設定儲存*貯體政策*，以允許公開讀取存取儲存貯體中的檔案。如需詳細資訊，請參閱[使用儲存貯體政策管理對 Amazon S3 儲存貯體的存取](examples-s3-bucket-policies.md)。

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_website_config.cpp)。

## 取得儲存貯體的網站組態
<a name="get-a-bucket-s-website-configuration"></a>

若要取得 Amazon S3 儲存貯體的網站組態，請使用 [GetBucketWebsiteRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_bucket_website_request.html) 呼叫 `S3Client`的 `GetBucketWebsite`函數，其中包含要擷取組態的儲存貯體名稱。

組態會在結果物件中傳回為 [GetBucketWebsiteResult](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_bucket_website_result.html) 物件。如果儲存貯體沒有網站組態，`null`則會傳回 。

 **Code** 

```
bool AwsDoc::S3::getWebsiteConfig(const Aws::String &bucketName,
                                  const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client s3Client(clientConfig);

    Aws::S3::Model::GetBucketWebsiteRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::GetBucketWebsiteOutcome outcome =
            s3Client.GetBucketWebsite(request);

    if (!outcome.IsSuccess()) {
        const Aws::S3::S3Error &err = outcome.GetError();

        std::cerr << "Error: GetBucketWebsite: "
                  << err.GetMessage() << std::endl;
    } else {
        Aws::S3::Model::GetBucketWebsiteResult websiteResult = outcome.GetResult();

        std::cout << "Success: GetBucketWebsite: "
                  << std::endl << std::endl
                  << "For bucket '" << bucketName << "':"
                  << std::endl
                  << "Index page : "
                  << websiteResult.GetIndexDocument().GetSuffix()
                  << std::endl
                  << "Error page: "
                  << websiteResult.GetErrorDocument().GetKey()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_website_config.cpp)。

## 刪除儲存貯體的網站組態
<a name="delete-a-bucket-s-website-configuration"></a>

若要刪除 Amazon S3 儲存貯體的網站組態，請使用 [DeleteBucketWebsiteRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_delete_bucket_website_request.html) 呼叫 `S3Client`的 `DeleteBucketWebsite`函數：包含要從中刪除組態的儲存貯體名稱。

 **Code** 

```
bool AwsDoc::S3::deleteBucketWebsite(const Aws::String &bucketName,
                                     const Aws::S3::S3ClientConfiguration &clientConfig) {
    Aws::S3::S3Client client(clientConfig);
    Aws::S3::Model::DeleteBucketWebsiteRequest request;
    request.SetBucket(bucketName);

    Aws::S3::Model::DeleteBucketWebsiteOutcome outcome =
            client.DeleteBucketWebsite(request);

    if (!outcome.IsSuccess()) {
        auto err = outcome.GetError();
        std::cerr << "Error: deleteBucketWebsite: " <<
                  err.GetExceptionName() << ": " << err.GetMessage() << std::endl;
    } else {
        std::cout << "Website configuration was removed." << std::endl;
    }

    return outcome.IsSuccess();
}
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_website_config.cpp)。

## 詳細資訊
<a name="more-information"></a>
+  Amazon Simple Storage Service API 參考中的 [PUT 儲存貯體網站](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html) 
+  Amazon Simple Storage Service API 參考中的 [GET 儲存貯體網站](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETwebsite.html) 
+  Amazon Simple Storage Service API 參考中的 [DELETE 儲存貯體網站](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEwebsite.html) 

# 將 TransferManager 用於 Amazon S3 操作
<a name="examples-s3-transfermanager"></a>

您可以使用 適用於 C\$1\$1 的 AWS SDK `TransferManager`類別可靠地將檔案從本機環境傳輸到 Amazon S3，並將物件從一個 Amazon S3 位置複製到另一個位置。 `TransferManager`可以取得傳輸進度，並暫停或繼續上傳和下載。

**注意**  
為了避免收取不完整或部分上傳的費用，建議您在 Amazon S3 儲存貯體上啟用 [AbortIncompleteMultipartUpload](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html) 生命週期規則。  
此規則會指示 Amazon S3 在啟動後的指定天數內中止未完成的分段上傳。超過設定的時間限制時，Amazon S3 會中止上傳，然後刪除不完整的上傳資料。  
如需詳細資訊，請參閱《Amazon S3 使用者指南》中的在[儲存貯體上設定生命週期組態](https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-set-lifecycle-configuration-intro.html)。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 使用 上傳和下載物件 `TransferManager`
<a name="stream"></a>

此範例示範如何在記憶體中[https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-transfer/html/class_aws_1_1_transfer_1_1_transfer_manager.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-transfer/html/class_aws_1_1_transfer_1_1_transfer_manager.html)傳輸大型物件。 `UploadFile`和 `DownloadFile`方法會以非同步方式呼叫，並傳回 `TransferHandle`來管理請求的狀態。如果上傳的物件大於 `bufferSize`，則會執行分段上傳。`bufferSize` 預設為 5MB，但可以透過 設定[https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-transfer/html/struct_aws_1_1_transfer_1_1_transfer_manager_configuration.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-transfer/html/struct_aws_1_1_transfer_1_1_transfer_manager_configuration.html)。

```
        auto s3_client = Aws::MakeShared<Aws::S3::S3Client>("S3Client");
        auto executor = Aws::MakeShared<Aws::Utils::Threading::PooledThreadExecutor>("executor", 25);
        Aws::Transfer::TransferManagerConfiguration transfer_config(executor.get());
        transfer_config.s3Client = s3_client;

        // Create buffer to hold data received by the data stream.
        Aws::Utils::Array<unsigned char> buffer(BUFFER_SIZE);

        // The local variable 'streamBuffer' is captured by reference in a lambda.
        // It must persist until all downloading by the 'transfer_manager' is complete.
        Stream::PreallocatedStreamBuf streamBuffer(buffer.GetUnderlyingData(), buffer.GetLength());

        auto transfer_manager = Aws::Transfer::TransferManager::Create(transfer_config);

        auto uploadHandle = transfer_manager->UploadFile(LOCAL_FILE, BUCKET, KEY, "text/plain", Aws::Map<Aws::String, Aws::String>());
        uploadHandle->WaitUntilFinished();
        bool success = uploadHandle->GetStatus() == Transfer::TransferStatus::COMPLETED; 
      
        if (!success)
        {
            auto err = uploadHandle->GetLastError();           
            std::cout << "File upload failed:  "<< err.GetMessage() << std::endl;
        }
        else
        {
            std::cout << "File upload finished." << std::endl;

            auto downloadHandle = transfer_manager->DownloadFile(BUCKET,
                KEY,
                [&]() { //Define a lambda expression for the callback method parameter to stream back the data.
                    return Aws::New<MyUnderlyingStream>("TestTag", &streamBuffer);
                });
            downloadHandle->WaitUntilFinished();// Block calling thread until download is complete.
            auto downStat = downloadHandle->GetStatus();
            if (downStat != Transfer::TransferStatus::COMPLETED)
            {
                auto err = downloadHandle->GetLastError();
                std::cout << "File download failed:  " << err.GetMessage() << std::endl;
            }
            std::cout << "File download to memory finished."  << std::endl;
```

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/transfer-manager/transferOnStream.cpp)。

# 使用 `S3CrtClient`進行 Amazon S3 操作
<a name="examples-s3-crt"></a>

`S3CrtClient` 類別可在 的 1.9 版中使用， 適用於 C\$1\$1 的 AWS SDK 並改善在 Amazon S3 之間上傳和下載大型資料檔案的輸送量。如需此版本改進的詳細資訊，請參閱[使用 v1 適用於 C\$1\$1 的 AWS SDK .9 改善 Amazon S3 輸送量 ](https://github.com/aws/aws-sdk-cpp/wiki/Improving-S3-Throughput-with-AWS-SDK-for-CPP-v1.9)

在[AWS 通用執行期 (CRT) 程式庫](https://docs.aws.amazon.com/sdkref/latest/guide/common-runtime.html)的頂端`S3CrtClient`實作 。

**注意**  
為了避免收取不完整或部分上傳的費用，建議您在 Amazon S3 儲存貯體上啟用 [AbortIncompleteMultipartUpload](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html) 生命週期規則。  
此規則會指示 Amazon S3 在啟動後的指定天數內中止未完成的分段上傳。超過設定的時間限制時，Amazon S3 會中止上傳，然後刪除不完整的上傳資料。  
如需詳細資訊，請參閱《Amazon S3 使用者指南》中的在[儲存貯體上設定生命週期組態](https://docs.aws.amazon.com/AmazonS3/latest/userguide/how-to-set-lifecycle-configuration-intro.html)。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 使用 上傳和下載物件 `S3CrtClient`
<a name="stream"></a>

此範例示範如何使用 [https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3-crt/html/class_aws_1_1_s3_crt_1_1_s3_crt_client.html](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3-crt/html/class_aws_1_1_s3_crt_1_1_s3_crt_client.html)。此範例會建立儲存貯體、上傳物件、下載物件，然後刪除檔案和儲存貯體。PUT 操作會變成分段上傳。GET 操作會變成多個「範圍」的 GET 請求。如需分段上傳的詳細資訊，請參閱《Amazon S3 使用者指南》中的[使用分段上傳上傳和複製物件](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html)。

在此範例中，提供的資料檔案 `ny.json`會以分段上傳的形式上傳。這可以透過在成功執行程式後檢視偵錯日誌來確認。

如果上傳失敗，`AbortMultipartUpload`則會在基礎 CRT 程式庫中發出 ，以清除任何已上傳的組件。不過，並非所有故障都可以在內部處理 （例如網路纜線已拔除）。建議您在 Amazon S3 儲存貯體上建立生命週期規則，以確保部分上傳的資料不會停留在您的帳戶 （部分上傳的資料仍應計費）。若要了解如何設定生命週期規則，請參閱[探索和刪除不完整的分段上傳以降低 Amazon S3 成本](https://aws.amazon.com/blogs/aws-cost-management/discovering-and-deleting-incomplete-multipart-uploads-to-lower-amazon-s3-costs/ )。

**使用偵錯日誌來探索分段上傳詳細資訊**

1. 在 中`main()`，請注意有「TODO」註解，其中包含更新程式碼的指示。

   1. 對於 `file_name`：從程式碼註解中提供的連結下載範例資料檔案 `ny.json`，或使用您自己的大型資料檔案。

   1. 對於 `region`：使用列舉將`region`變數更新為 AWS 區域 帳戶的 。若要尋找您帳戶的 區域，請登入 AWS 管理主控台，並在右上角找到 區域。

1. 建置範例。

1. 將變數指定的檔案複製到`file_name`可執行檔資料夾，然後執行`s3-crt-demo`可執行檔。

1. 在您的可執行檔資料夾中，尋找最新的 `.log` 檔案。

1. 開啟日誌檔案，選取**搜尋**，然後輸入 **partNumber**。

1. 日誌包含類似下列的項目，其中`uploadId`會針對上傳檔案的每個部分指定 `partNumber`和 ：

    `PUT /my-object partNumber=1&uploadId=gsk8vDbmnlA5EseDo._LDEgq22Qmt0SeuszYxMsZ9ABt503VqDIFOP8xzZI1P0zp.ToS.qo5kK16HNWogZF3KpRo.Dc7QnLZIK0BTmzCWwWoPax4T21hvP6nPdz9591F content-length:8388608 host:my-bucketasdfasdf.s3.us-east-2.amazonaws.com x-amz-content-sha256:UNSIGNED-PAYLOAD`

    及 

    `PUT /my-object partNumber=2&uploadId=gsk8vDbmnlA5EseDo._LDEgq22Qmt0SeuszYxMsZ9ABt503VqDIFOP8xzZI1P0zp.ToS.qo5kK16HNWogZF3KpRo.Dc7QnLZIK0BTmzCWwWoPax4T21hvP6nPdz9591F content-length:8388608 host:my-bucketasdfasdf.s3.us-east-2.amazonaws.com x-amz-content-sha256:UNSIGNED-PAYLOAD `

請參閱 GitHub 上的[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3-crt/s3-crt-demo.cpp)。

# 使用 的 Amazon SQS 程式碼範例 適用於 C\$1\$1 的 AWS SDK
<a name="examples-sqs"></a>

Amazon Simple Queue Service (Amazon SQS) 是一種全受管訊息佇列服務，可讓您輕鬆分離和擴展微服務、分散式系統和無伺服器應用程式。您可以使用下列範例，使用 編寫 [Amazon SQS](https://aws.amazon.com/sqs) 的程式 適用於 C\$1\$1 的 AWS SDK。

**注意**  
本指南僅提供示範特定技術所需的程式碼，但[完整的範例程式碼可在 GitHub 上取得](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。在 GitHub 上，您可以下載單一來源檔案，也可以在本機複製儲存庫，以取得、建置和執行所有範例。

**Topics**
+ [使用 Amazon SQS 訊息佇列](examples-sqs-message-queues.md)
+ [傳送、接收和刪除 Amazon SQS 訊息](examples-sqs-messages.md)
+ [啟用 Amazon SQS 訊息佇列的長輪詢](examples-sqs-long-polling.md)
+ [在 Amazon SQS 中設定可見性逾時](examples-sqs-visibility-timeout.md)
+ [在 Amazon SQS 中使用無效字母佇列](examples-sqs-dead-letter-queues.md)

# 使用 Amazon SQS 訊息佇列
<a name="examples-sqs-message-queues"></a>

*訊息佇列*是您用來在 Amazon SQS 中可靠傳送訊息的邏輯容器。有兩種佇列類型：*標準*和*先進先出* (FIFO)。若要進一步了解佇列和這些類型之間的差異，請參閱 [Amazon Simple Queue Service 開發人員指南](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/)。

這些 C\$1\$1 範例示範如何使用 適用於 C\$1\$1 的 AWS SDK 來建立、列出、刪除和取得 Amazon SQS 佇列的 URL。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立佇列
<a name="sqs-create-queue"></a>

使用 SQSClient 類別`CreateQueue`成員函數，並提供描述佇列參數的 [CreateQueueRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_create_queue_request.html) 物件。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/CreateQueueRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::CreateQueueRequest request;
    request.SetQueueName(queueName);

    const Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created queue " << queueName << " with a queue URL "
                  << outcome.GetResult().GetQueueUrl() << "." << std::endl;
    }
    else {
        std::cerr << "Error creating queue " << queueName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/create_queue.cpp)。

## 列出佇列
<a name="sqs-list-queues"></a>

若要列出帳戶的 Amazon SQS 佇列，請呼叫 SQSClient 類別`ListQueues`成員函數，並將其傳遞 [ListQueuesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_list_queues_request.html) 物件。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ListQueuesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::ListQueuesRequest listQueuesRequest;

    Aws::String nextToken; // Used for pagination.
    Aws::Vector<Aws::String> allQueueUrls;

    do {
        if (!nextToken.empty()) {
            listQueuesRequest.SetNextToken(nextToken);
        }
        const Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues(
                listQueuesRequest);
        if (outcome.IsSuccess()) {
            const Aws::Vector<Aws::String> &queueUrls = outcome.GetResult().GetQueueUrls();
            allQueueUrls.insert(allQueueUrls.end(),
                                queueUrls.begin(),
                                queueUrls.end());

            nextToken = outcome.GetResult().GetNextToken();
        }
        else {
            std::cerr << "Error listing queues: " <<
                      outcome.GetError().GetMessage() << std::endl;
            return false;
        }

    } while (!nextToken.empty());

    std::cout << allQueueUrls.size() << " Amazon SQS queue(s) found." << std::endl;
    for (const auto &iter: allQueueUrls) {
        std::cout << " " << iter << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/list_queues.cpp)。

## 取得佇列的 URL
<a name="sqs-get-queue-url"></a>

若要取得現有 Amazon SQS 佇列的 URL，請呼叫 SQSClient 類別`GetQueueUrl`成員函數。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/GetQueueUrlRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::GetQueueUrlRequest request;
    request.SetQueueName(queueName);

    const Aws::SQS::Model::GetQueueUrlOutcome outcome = sqsClient.GetQueueUrl(request);
    if (outcome.IsSuccess()) {
        std::cout << "Queue " << queueName << " has url " <<
                  outcome.GetResult().GetQueueUrl() << std::endl;
    }
    else {
        std::cerr << "Error getting url for queue " << queueName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/get_queue_url.cpp)。

## 刪除佇列
<a name="sqs-delete-queue"></a>

將 [URL](#sqs-get-queue-url) 提供給 SQSClient 類別`DeleteQueue`成員函數。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/core/client/DefaultRetryStrategy.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/DeleteQueueRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::Model::DeleteQueueRequest request;
    request.SetQueueUrl(queueURL);

    const Aws::SQS::Model::DeleteQueueOutcome outcome = sqsClient.DeleteQueue(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted queue with url " << queueURL <<
                  std::endl;
    }
    else {
        std::cerr << "Error deleting queue " << queueURL << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/delete_queue.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  《[Amazon Simple Queue Service 開發人員指南》中的 Amazon SQS 佇列如何運作](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-how-it-works.html) 
+  Amazon Simple Queue Service API 參考中的 [CreateQueue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html)
+  Amazon Simple Queue Service API 參考中的 [GetQueueUrl](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueUrl.html) 
+  Amazon Simple Queue Service API 參考中的 [ListQueues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ListQueues.html) 
+  Amazon Simple Queue Service API 參考中的 [DeleteQueues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteQueues.html) 

# 傳送、接收和刪除 Amazon SQS 訊息
<a name="examples-sqs-messages"></a>

訊息一律使用 [SQS 佇列](examples-sqs-message-queues.md)傳遞。這些 C\$1\$1 範例說明如何使用 適用於 C\$1\$1 的 AWS SDK 來傳送、接收和刪除 SQS 佇列中的 Amazon SQS 訊息。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 傳送訊息
<a name="sqs-message-send"></a>

您可以呼叫 Amazon SQS SQSClient 佇列。 `SendMessage``SendMessage` 您提供 [SendMessageRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_send_message_request.html) 物件，其中包含佇列的 [URL](examples-sqs-message-queues.md#sqs-get-queue-url)、訊息內文和選用的延遲值 （以秒為單位）。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/SendMessageRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::SendMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetMessageBody(messageBody);

    const Aws::SQS::Model::SendMessageOutcome outcome = sqsClient.SendMessage(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully sent message to " << queueUrl <<
                  std::endl;
    }
    else {
        std::cerr << "Error sending message to " << queueUrl << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/send_message.cpp)。

## 接收訊息
<a name="sqs-messages-receive"></a>

呼叫 SQSClient 類別`ReceiveMessage`成員函數，將佇列的 URL 傳遞給佇列，以擷取目前佇列中的任何訊息。訊息會以 [Message](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_message.html) 物件清單的形式傳回。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ReceiveMessageRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::ReceiveMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetMaxNumberOfMessages(1);

    const Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage(
            request);
    if (outcome.IsSuccess()) {

        const Aws::Vector<Aws::SQS::Model::Message> &messages =
                outcome.GetResult().GetMessages();
        if (!messages.empty()) {
            const Aws::SQS::Model::Message &message = messages[0];
            std::cout << "Received message:" << std::endl;
            std::cout << "  MessageId: " << message.GetMessageId() << std::endl;
            std::cout << "  ReceiptHandle: " << message.GetReceiptHandle() << std::endl;
            std::cout << "  Body: " << message.GetBody() << std::endl << std::endl;
        }
        else {
            std::cout << "No messages received from queue " << queueUrl <<
                      std::endl;

        }
    }
    else {
        std::cerr << "Error receiving message from queue " << queueUrl << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/receive_message.cpp)。

### 接收後刪除訊息
<a name="sqs-messages-delete"></a>

收到訊息並處理其內容後，透過將訊息的接收控點和佇列 URL 傳送至 SQSClient 類別`DeleteMessage`成員函數，從佇列刪除訊息。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/DeleteMessageRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::Model::DeleteMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetReceiptHandle(messageReceiptHandle);

    const Aws::SQS::Model::DeleteMessageOutcome outcome = sqsClient.DeleteMessage(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted message from queue " << queueUrl
                  << std::endl;
    }
    else {
        std::cerr << "Error deleting message from queue " << queueUrl << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/receive_message.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  《[Amazon Simple Queue Service 開發人員指南》中的 Amazon SQS 佇列如何運作](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-how-it-works.html) 
+  Amazon Simple Queue Service API 參考中的 [SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html) 
+  Amazon Simple Queue Service API 參考中的 [SendMessageBatch](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html) 
+  Amazon Simple Queue Service API 參考中的 [ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html) 
+  Amazon Simple Queue Service API 參考中的 [DeleteMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteMessage.html) 

# 啟用 Amazon SQS 訊息佇列的長輪詢
<a name="examples-sqs-long-polling"></a>

Amazon SQS 預設會使用*短輪詢*，根據加權隨機分佈僅查詢伺服器子集，以判斷回應中是否有任何訊息可供納入。

當沒有訊息可傳回以回覆傳送至 Amazon SQS 佇列的 ReceiveMessage 請求，並消除錯誤的空回應時，長輪詢有助於降低使用 Amazon SQS 的成本。您可以將長輪詢頻率設定為 *1-20 秒*。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立佇列時啟用長輪詢
<a name="sqs-long-polling-create-queue"></a>

若要在建立 Amazon SQS 佇列時啟用長輪詢，請在 [CreateQueueRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_create_queue_request.html) 物件上設定 `ReceiveMessageWaitTimeSeconds` 屬性，然後再呼叫 SQSClient 類別`CreateQueue`的成員函數。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/CreateQueueRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::CreateQueueRequest request;
    request.SetQueueName(queueName);
    request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds,
            pollTimeSeconds);

    const Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully created queue " << queueName <<
                  std::endl;
    }
    else {
        std::cout << "Error creating queue " << queueName << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/long_polling_on_create_queue.cpp)。

## 在現有佇列上啟用長輪詢
<a name="sqs-long-polling-existing-queue"></a>

除了在建立佇列時啟用長輪詢之外，您也可以在呼叫 SQSClient 類別`SetQueueAttributes`的成員函數之前，在 [SetQueueAttributesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_set_queue_attributes_request.html) `ReceiveMessageWaitTimeSeconds` 上設定 ，在現有佇列上啟用它。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/SetQueueAttributesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(clientConfiguration);

    Aws::SQS::Model::SetQueueAttributesRequest request;
    request.SetQueueUrl(queueURL);
    request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds,
            pollTimeSeconds);

    const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(
            request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully updated long polling time for queue " <<
                  queueURL << " to " << pollTimeSeconds << std::endl;
    }
    else {
        std::cout << "Error updating long polling time for queue " <<
                  queueURL << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/long_polling_on_existing_queue.cpp)。

## 在收到訊息時啟用長輪詢
<a name="sqs-long-polling-receive-message"></a>

您可以在接收訊息時啟用長輪詢，方法是在提供給 SQSClient 類別的 [ReceiveMessageRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_receive_message_request.html) 上設定以秒為單位的等待時間。 ReceiveMessage 

**注意**  
您應該確保 AWS 用戶端的請求逾時大於最長長輪詢時間 (20 秒），讓您的`ReceiveMessage`請求在等待下一個輪詢事件時不會逾時！

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ReceiveMessageRequest.h>
```

 **Code** 

```
    Aws::SQS::SQSClient sqsClient(customConfiguration);

    Aws::SQS::Model::ReceiveMessageRequest request;
    request.SetQueueUrl(queueUrl);
    request.SetMaxNumberOfMessages(1);
    request.SetWaitTimeSeconds(waitTimeSeconds);

    auto outcome = sqsClient.ReceiveMessage(request);
    if (outcome.IsSuccess()) {
        const auto &messages = outcome.GetResult().GetMessages();
        if (messages.empty()) {
            std::cout << "No messages received from queue " << queueUrl <<
                      std::endl;
        }
        else {
            const auto &message = messages[0];
            std::cout << "Received message:" << std::endl;
            std::cout << "  MessageId: " << message.GetMessageId() << std::endl;
            std::cout << "  ReceiptHandle: " << message.GetReceiptHandle() << std::endl;
            std::cout << "  Body: " << message.GetBody() << std::endl << std::endl;
        }
    }
    else {
        std::cout << "Error receiving message from queue " << queueUrl << ": "
                  << outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/long_polling_on_message_receipt.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  《[Amazon Simple Queue Service 開發人員指南》中的 Amazon SQS 長輪詢](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html) 
+  Amazon Simple Queue Service API 參考中的 [CreateQueue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html)
+  Amazon Simple Queue Service API 參考中的 [ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html) 
+  Amazon Simple Queue Service API 參考中的 [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html) 

# 在 Amazon SQS 中設定可見性逾時
<a name="examples-sqs-visibility-timeout"></a>

在 Amazon SQS 中收到訊息時，訊息會保留在佇列中，直到刪除為止，以確保接收。在指定的*可見性逾時*後，後續請求中將可取得已接收但未刪除的訊息，以協助防止訊息在處理和刪除之前收到超過一次。

使用[標準佇列](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/standard-queues.html)時，可見性逾時並不保證不會收到訊息兩次。如果您使用的是標準佇列，請確定您的程式碼可以處理相同訊息已交付多次的情況。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 在收到訊息時設定訊息可見性逾時
<a name="sqs-visibility-timeout-receipt"></a>

當您收到訊息時，您可以在傳遞給 SQSClient 類別`ChangeMessageVisibility`成員函數的 [ChangeMessageVisibilityRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_change_message_visibility_request.html) 中傳遞其接收控制代碼，以修改其可見性逾時。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/ChangeMessageVisibilityRequest.h>
#include <aws/sqs/model/ReceiveMessageRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::Model::ChangeMessageVisibilityRequest request;
    request.SetQueueUrl(queue_url);
    request.SetReceiptHandle(messageReceiptHandle);
    request.SetVisibilityTimeout(visibilityTimeoutSeconds);

    auto outcome = sqsClient.ChangeMessageVisibility(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully changed visibility of message " <<
                  messageReceiptHandle << " from queue " << queue_url << std::endl;
    }
    else {
        std::cout << "Error changing visibility of message from queue "
                  << queue_url << ": " <<
                  outcome.GetError().GetMessage() << std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/change_message_visibility.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  Amazon Simple Queue Service 開發人員指南中的[可見性逾時](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html) 
+  Amazon Simple Queue Service API 參考中的 [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html) 
+  Amazon Simple Queue Service API 參考中的 [GetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html) 
+  Amazon Simple Queue Service API 參考中的 [ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html) 
+  Amazon Simple Queue Service API 參考中的 [ChangeMessageVisibility](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ChangeMessageVisibility.html) 
+  Amazon Simple Queue Service API 參考中的 [ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ChangeMessageVisibilityBatch.html) 

# 在 Amazon SQS 中使用無效字母佇列
<a name="examples-sqs-dead-letter-queues"></a>

Amazon SQS 支援*無效字母佇列*。無效字母佇列是其他佇列可以為無法成功處理的訊息設定目標的佇列。您可以在無效字母佇列中擱置並隔離這類訊息，以確定無法成功處理訊息的原因。

若要建立無效字母佇列，您必須先建立*再驅動政策*，然後在佇列的屬性中設定政策。

**重要**  
無效字母佇列必須是與來源佇列相同的佇列類型 (FIFO 或標準）。它也必須使用與來源佇列相同的 AWS 帳戶 和 AWS 區域 建立。

## 先決條件
<a name="codeExamplePrereq"></a>

開始之前，建議您先閱讀[開始使用 適用於 C\$1\$1 的 AWS SDK](getting-started.md)。

下載範例程式碼並建置解決方案，如中所述[程式碼範例入門](getting-started-code-examples.md)。

若要執行範例，您的程式碼用來提出請求的使用者描述檔必須具有 AWS （針對 服務和 動作） 的適當許可。如需詳細資訊，請參閱[提供 AWS 登入](credentials.md)資料。

## 建立再驅動政策
<a name="sqs-dead-letter-queue-create-redrive-policy"></a>

再驅動政策是在 JSON 中指定。若要建立它，您可以使用 隨附的 JSON 公用程式類別 適用於 C\$1\$1 的 AWS SDK。

以下是建立再驅動政策的範例函數，方法是提供無效字母佇列的 ARN，以及在傳送至無效字母佇列之前可接收和處理訊息的次數上限。

 **包括** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/json/JsonSerializer.h>
```

 **Code** 

```
Aws::String MakeRedrivePolicy(const Aws::String &queueArn, int maxReceiveCount) {
    Aws::Utils::Json::JsonValue redrive_arn_entry;
    redrive_arn_entry.AsString(queueArn);

    Aws::Utils::Json::JsonValue max_msg_entry;
    max_msg_entry.AsInteger(maxReceiveCount);

    Aws::Utils::Json::JsonValue policy_map;
    policy_map.WithObject("deadLetterTargetArn", redrive_arn_entry);
    policy_map.WithObject("maxReceiveCount", max_msg_entry);

    return policy_map.View().WriteReadable();
}
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/dead_letter_queue.cpp)。

## 在來源佇列上設定再驅動政策
<a name="sqs-dead-letter-queue-set-redrive-policy"></a>

若要完成無效字母佇列的設定，請使用 [SetQueueAttributesRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-sqs/html/class_aws_1_1_s_q_s_1_1_model_1_1_set_queue_attributes_request.html) 物件呼叫 SQSClient 類別`SetQueueAttributes`的成員函數，您已使用 JSON 再驅動政策設定 `RedrivePolicy` 屬性。

 **包括** 

```
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/SetQueueAttributesRequest.h>
#include <iostream>
```

 **Code** 

```
    Aws::SQS::Model::SetQueueAttributesRequest request;
    request.SetQueueUrl(srcQueueUrl);
    request.AddAttributes(
            Aws::SQS::Model::QueueAttributeName::RedrivePolicy,
            redrivePolicy);

    const Aws::SQS::Model::SetQueueAttributesOutcome outcome =
            sqsClient.SetQueueAttributes(request);
    if (outcome.IsSuccess()) {
        std::cout << "Successfully set dead letter queue for queue  " <<
                  srcQueueUrl << " to " << deadLetterQueueARN << std::endl;
    }
    else {
        std::cerr << "Error setting dead letter queue for queue " <<
                  srcQueueUrl << ": " << outcome.GetError().GetMessage() <<
                  std::endl;
    }
```

請參閱[完整範例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sqs/dead_letter_queue.cpp)。

## 詳細資訊
<a name="more-info"></a>
+  《[Amazon Simple Queue Service 開發人員指南》中的使用 Amazon SQS 無效字母](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html)佇列
+  Amazon Simple Queue Service API 參考中的 [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html) 