

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# AWS 服务 使用适用于 C\$1\$1 的 AWS SDK 进行调用的指导示例
<a name="programming-services"></a>

如果您不熟悉 AWS AWS 代码示例，我们建议您从开始[代码示例入门](getting-started-code-examples.md)。

显示如何使用 AWS 服务的源代码可在本指南的 适用于 C\$1\$1 的 AWS SDK [代码示例](cpp_code_examples.md)章节中找到，也可以直接在上的[AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code)中找到 GitHub。

本节选择了几种 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 文档团队提出新的代码示例，请参阅创建新请求的[贡献指南](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/CONTRIBUTING.md)。 GitHub 团队更倾向于创建展示完整场景的代码示例，而非仅演示单个 API 调用的示例。

**在 Windows 上使用代码示例**

如果您要在 Windows 上使用 SDK 版本 1.9 构建示例，请参阅[解决 AWS 适用于 C\$1\$1 的 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's `ListMetrics` 函数。您可以使用 `ListMetricsRequest` 通过命名空间、指标名称或维度筛选返回的指标。

**注意**  
 AWS 服务发布的指标和维度列表可在亚马逊 CloudWatch 用户指南的 “[亚马逊 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>
```

 **代码** 

```
        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();
        }
```

[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)通过调用其`GetMetrics`函数在 a 中返回这些指标。结果可以*分页*。要检索下一批结果，请在原始请求对象中使用 `ListMetricsResult` 对象的 `GetNextToken` 函数的返回值调用 `SetNextToken`，并将已修改的请求对象传回对 `ListMetrics` 的另一个调用。

请参阅[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/cloudwatch/list_metrics.cpp)。

## 更多信息
<a name="more-information"></a>
+  [ListMetrics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/ListMetrics.html)在《亚马逊 CloudWatch API 参考》中。

# 发布自定义指标数据
<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>

要发布您自己的指标数据，请使用调用 CloudWatchClient's `PutMetricData` 函数[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)。`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>
```

 **代码** 

```
        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>
+  [使用亚马逊 CloudWatch 用户指南中的亚马逊 CloudWatch 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)。
+ AWS Amazon CloudWatch 用户指南中的@@ [命名空间](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/aws-namespaces.html)。
+  [PutMetricData](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/PutMetricData.html)在《亚马逊 CloudWatch API 参考》中。

# 处理 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 指标创建警报，请调用[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)填充警报条件 CloudWatchClient的's `PutMetricAlarm` 函数。

 **包含** 

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

 **代码** 

```
        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 警报，请调用 CloudWatchClient's `DescribeAlarms` 函数 [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)，您可以使用该函数为结果设置选项。

 **包含** 

```
#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>
```

 **代码** 

```
        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();
        }
```

可以通过调用`getMetricAlarms`返回的来获取警报列表`DescribeAlarms`。[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)

结果可以*分页*。要检索下一批结果，请在原始请求对象中使用 `DescribeAlarmsResult` 对象的 `GetNextToken` 函数的返回值调用 `SetNextToken`，并将已修改的请求对象传回对 `DescribeAlarms` 的另一个调用。

**注意**  
您还可以使用 CloudWatchClient's `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)包含一个或多个要删除的警报名称的`DeleteAlarms`函数。 CloudWatchClient

 **包含** 

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

 **代码** 

```
        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>
+  在@@ [亚马逊 CloudWatch 用户指南中创建亚马逊 CloudWatch 警报](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html)
+  [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)在 Amazon CloudWatch API 参考中

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

使用 CloudWatch 警报操作，您可以创建执行自动停止、终止、重启或恢复 Amazon EC2 实例等操作的警报。

[创建警报时，可以使用[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`功能将警报操作添加到警报中](examples-cloudwatch-create-alarms.md)。

## 先决条件
<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 警报操作，请`EnableAlarmActions`使用[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

 **包含** 

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

 **代码** 

```
    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 警报操作，请`DisableAlarmActions`使用[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

 **包含** 

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

 **代码** 

```
        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)
+  [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)在 Amazon CloudWatch API 参考中

# 将事件发送到 CloudWatch
<a name="examples-cloudwatch-send-events"></a>

CloudWatch 事件提供近乎实时的系统事件流，这些事件描述了亚马逊 EC2 实例、Lambda 函数、Kinesis 流、亚马逊 ECS 任务、Step Functions 状态机、亚马逊 SNS 主题、亚马逊 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)或多个提供每个事件详细信息的[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)对象调用 CloudWatchEventsClient's `PutEvents` 函数。您可以为条目指定多个参数，例如事件的来源和类型、与事件相关联的资源等等。

**注意**  
对于每个 `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>
```

 **代码** 

```
        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)带有规则名称和可选参数（例如[事件模式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html)、要与规则关联的 IAM 角色以及描述规则运行频率的[计划表达式）调](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html)用 CloudWatchEventsClient's `PutRule` 函数。

 **包含** 

```
#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>
```

 **代码** 

```
        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 状态机和内置目标。

要向规则添加目标，请调用 CloudWatchEventsClient's `PutTargets` 函数，[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)其中包含要更新的规则和要添加到规则中的目标列表。

 **包含** 

```
#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>
```

 **代码** 

```
        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 [E PutEvents vents 用户指南中使用添加 CloudWatch 事件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/AddEventsPutEvents.html)
+  在 Amazon [ CloudWatch Events 用户指南中安排规则表达式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html)
+  Amazon [Events 用户指南中的 CloudWatch CloudWatch 事件类型](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/EventTypes.html)
+  Amazon [Events 用户指南中的 CloudWatch 事件和事件模式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEventsandEventPatterns.html)
+  [PutEvents](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutEvents.html)在 Amazon Event CloudWatch s API 参考中
+  [PutTargets](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutTargets.html)在 Amazon Event CloudWatch s API 参考中
+  [PutRule](https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/PutRule.html)在 Amazon Event CloudWatch s API 参考中

# 使用以下内容的亚马逊 DynamoDB 示例 适用于 C\$1\$1 的 AWS SDK
<a name="examples-dynamodb"></a>

Amazon DynamoDB 是一种全托管 NoSQL 数据库服务，提供快速而可预测的性能，能够实现无缝扩展。以下示例展示了如何使用 适用于 C\$1\$1 的 AWS SDK对 [Amazon DynamoDB](https://aws.amazon.com/dynamodb) 进行编程。

**注意**  
本指南中仅提供了演示某些技术所需的代码，但[完整的示例代码可在上找到 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)。
+  *预置吞吐量*值，用于定义表的预留 read/write 容量单位数。
**注意**  
 [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。

### 创建具有简单主键的表
<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>
```

 **代码** 

```
//! 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>
```

 **代码** 

```
//! 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);
}
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/create_table_composite_key.cpp) GitHub。

## 列出表
<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>
```

 **代码** 

```
//! 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>
```

 **代码** 

```
//! 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();
}
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/describe_table.cpp) GitHub。

## 修改表
<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>
```

 **代码** 

```
//! 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>
```

 **代码** 

```
//! 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();
}
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/delete_table.cpp) GitHub。

## 更多信息
<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 中的项目
<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>
```

 **代码** 

```
//! 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();
}
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/get_item.cpp) GitHub。

## 向表中添加项目
<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)对。其中必须包括表的主键字段的值。如果主键标识的项目已存在，那么其字段将通过该请求*更新*。[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)使用`AddItem`方法将它们添加到中。

 **包含** 

```
#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>
```

 **代码** 

```
//! 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);
}
```

请参阅上的[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/dynamodb/put_item.cpp) GitHub。

## 更新表中现有项目
<a name="dynamodb-update-item"></a>

您可以使用 Dynamo 的`UpdateItem`方法更新表中已存在DBClient的项目的属性，提供表名、主键值和要更新的字段及其对应的值。

 **导入** 

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

 **代码** 

```
//! 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)

# 使用 Amazon EC2 的示例 适用于 C\$1\$1 的 AWS SDK
<a name="examples-ec2"></a>

Amazon Elastic Compute Cloud（Amazon EC2）是一项 Web 服务，可提供大小可调节的计算容量（确切地说，即 Amazon 数据中心的服务器），您可以使用它来构建和托管您的软件系统。您可以使用以下示例通过 适用于 C\$1\$1 的 AWS SDK对 [Amazon EC2](https://aws.amazon.com/ec2) 进行编程。

**注意**  
本指南中仅提供了演示某些技术所需的代码，但[完整的示例代码可在上找到 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)
+ [将区域和可用区用于 &EC2](examples-ec2-regions-zones.md)
+ [使用 &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>

通过调用 EC2客户端的`RunInstances`函数，为其提供[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)包含要使用的[亚马逊系统映像 (AMI)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html) 和[实例类型](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html)来创建新的 Amazon EC2 实例。

 **包含** 

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

 **代码** 

```
    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 实例，请调用 EC2客户端的`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>
```

 **代码** 

```
    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 实例，请调用 EC2客户端的`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>
```

 **代码** 

```
    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 实例，请调用 EC2客户端的`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>
```

 **代码** 

```
    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)并调用 EC2客户端的`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` 函数，然后对每个返回的 Reservation 对象调用 `getInstances`。

 **包含** 

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

 **代码** 

```
    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 用户指南》中的[监控 Amazon EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring_ec2.html)。

要开始监控实例，您必须[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)使用要监控的实例的 ID 创建一个，并将其传递给 EC2客户端的`MonitorInstances`函数。

 **包含** 

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

 **代码** 

```
    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>

要停止监控实例，请[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)使用要停止监控的实例 ID 创建一个，然后将其传递给 EC2客户端的`UnmonitorInstances`函数。

 **包含** 

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

 **代码** 

```
    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>
+  [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 API 参考中

# 在 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 地址，请使用包含网络类型（经典 EC2 或 VPC）的[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客户端`AllocateAddress`函数。

**警告**  
我们将于 2022 年 8 月 15 日停用 EC2-Classic。我们建议您从 EC2-Classic 迁移到 VPC。有关更多信息，请参阅[适用于 Linux 实例的 Amazon EC2 用户指南](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-migrate.html)或[适用于 Windows 实例的 Amazon EC2 用户指南](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/vpc-migrate.html)中的**从 EC2-Classic 迁移到 VPC**。另请参阅 [EC2-Classic Networking is Retiring – Here's How to Prepare](https://aws.amazon.com/blogs/aws/ec2-classic-is-retiring-heres-how-to-prepare/) 博客文章。

response 对象中的[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，通过将分配 ID 和实例 ID 传递给 EC2客户端的`AssociateAddress`函数，您可以使用该分配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)将地址与实例相关联。

 **包含** 

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

 **代码** 

```
    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 地址，请调用 EC2客户端`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>
```

 **代码** 

```
    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 地址，请调用 EC2客户端的`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>
```

 **代码** 

```
    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 地址而不将其释放，请使用 EC2客户端的`DisassociateAddress`函数。

如果您使用的是非默认 VPC，则*必须*使用 `DisassociateAddress` 取消弹性 IP 地址的关联，然后再尝试释放它。否则，Amazon EC2 会返回错误（*无效IPAddress。 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)
+  [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 API 参考中

# 将区域和可用区用于 &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 账户，请使用调用 EC2客户端`DescribeRegions`函数[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)。

你将在结果对象[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` 函数以获取代表每个区域的 [Region](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>
```

 **代码** 

```
    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>

要列出您的账户可用的每个可用区，请使用调用 EC2客户端`DescribeAvailabilityZones`函数[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)。

你将在结果对象[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>
```

 **代码** 

```
    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)
+  [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 API 参考中

# 使用 &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>

要创建密钥对，请使用包含密钥名称的调用 EC2客户端`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)

 **包含** 

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

 **代码** 

```
    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>

要列出您的密钥对或获取有关密钥对的信息，请使用调用 EC2客户端`DescribeKeyPairs`函数[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)。

您将收到一个 [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>
```

 **代码** 

```
    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>

要删除密钥对，请调用 EC2 Client 端的`DeleteKeyPair`函数，向其传递 a [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>
```

 **代码** 

```
    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)
+  [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 API 参考中

# 使用 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>

要创建安全组，请使用包含密钥名称的调用 EC2客户端`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)

 **包含** 

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

 **代码** 

```
    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 实例的入站（入口）流量和出站（出口）流量。

要向您的安全组添加入口规则，请使用 EC2客户端的`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>
```

 **代码** 

```
    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;
    }
```

要向安全组添加出口规则，请在 EC2客户端`AuthorizeSecurityGroupEgress`函数中[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)提供类似的数据。

请参阅[完整示例](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/ec2/create_security_group.cpp)。

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

要描述您的安全组或获取有关安全组的信息，请使用调用 EC2客户端`DescribeSecurityGroups`函数[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)。

您将在结果对象[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>
```

 **代码** 

```
    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>

要删除安全组，请调用 EC2客户端的`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>
```

 **代码** 

```
    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 用户指南》中的[为您的 Linux 实例授权入站流量](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-instance.html)
+  [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 EC2 API 参考中

# 使用 Amazon S3 代码示例 适用于 C\$1\$1 的 AWS SDK
<a name="examples-s3"></a>

[Amazon S3](https://aws.amazon.com/s3) 是专为从任意位置存储和检索任意数量的数据而构建的对象存储。提供了多个类来与 Amazon S3 接口。 适用于 C\$1\$1 的 AWS SDK 

**注意**  
本指南中仅提供了演示某些技术所需的代码，但[完整的示例代码可在上找到 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`示例专门针对在 CURL 开启的情况下使用 Linux/Mac （尽管可以修改为在 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 版本中被引入。`S3CrtClient` 为 Amazon S3 的 GET（下载）和 PUT（上传）操作提供高吞吐量。`S3CrtClient`是在 AWS 公共运行时 (CRT) 库的顶部实现的。

  使用 `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()` 方法。如果成功，该方法将返回一个包含 `ListBucketResult` 对象的 `ListBucketOutcome` 对象。`ListBucketResult` 对象会调用 `GetBuckets()` 方法以获取包含您账户中每个 Amazon S3 存储桶信息的 `Bucket` 对象列表。

 **代码** 

```
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()` 中，您需要使用 `enum` 将 AWS 区域 更改为账户所在区域。您可以登录[AWS 管理控制台](https://console.aws.amazon.com/)查看账户所在区域，然后在右上角找到该区域。
+ `CreateBucket()` 使用 SDK 创建存储桶。



`S3Client` 对象调用 SDK 的 `CreateBucket()` 方法，传入带有存储桶名称的 `CreateBucketRequest`。默认情况下，存储桶在 *us-east-1*（弗吉尼亚州北部）区域创建。如果您的区域不是 *us-east-1*，则代码会设置存储桶约束，以确保在您所在地区创建存储桶。

 **代码** 

```
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()` 中，您需要使用 `enum` 将 AWS 区域 更改为账户所在区域。您还需要将 `bucket_name` 更改为要删除的存储桶的名称。
+ `DeleteBucket()` 使用 SDK 删除存储桶。



`S3Client` 对象使用 SDK 的 `DeleteBucket()` 方法，并传入一个带有要删除的存储桶名称的 `DeleteBucketRequest` 对象。存储桶必须为空才能成功。

 **代码**

```
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)

 **代码** 

```
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)

 **代码** 

```
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` 实例的形式获取对象列表。

 **代码** 

```
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/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_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/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 下载对象。对象内容存储在局部变量中，内容的第一行将输出到控制台。

 **代码** 

```
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` 对象，该对象需设置要删除的存储桶名称和对象键。*指定的存储桶和对象键必须存在，否则将出现错误*。

 **代码** 

```
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 指定了 bucket/object 的所有者和授权列表。每个授权项都指定一名用户（或被授权者）以及该用户访问存储桶/对象的权限，例如读取或写入权限。

## 先决条件
<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。

以下代码使用 `GetObjectAcl` 检索到的 ACL，并为其添加新的授权项。用户或被授权者被授予该对象的读取权限。修改后的 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，`PutBucketAcl` 对存储桶应用新的 ACL。

以下代码演示如何获取和设置存储桶 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>

您可以为特定 S3 存储桶设置存储桶策略，方法`S3Client`是调用`PutBucketPolicy`函数并在中为其提供存储桶名称和策略的 JSON 表示形式[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)。

 **代码** 

```
//! 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`'s `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)。

 **代码** 

```
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`'s `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)。

 **代码** 

```
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>
+  [PutBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/PutBucketPolicy.html)在 Amazon 简单存储服务 API 参考中
+  [GetBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/GetBucketPolicy.html)在 Amazon 简单存储服务 API 参考中
+  [DeleteBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/DeleteBucketPolicy.html)在 Amazon 简单存储服务 API 参考中
+  《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 存储桶的网站配置，请使用[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)对象中提供的包含存储桶名称及其网站配置的[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)对象调用 `S3Client`'s `PutBucketWebsite` 函数。

设置索引文档是*必需的*；所有其他参数都是可选的。

 **代码** 

```
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 存储桶`S3Client`的网站配置，请调用[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)包含要检索配置的存储桶名称的's `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`。

 **代码** 

```
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`'s `DeleteBucketWebsite` 函数。

 **代码** 

```
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 参考》中的 [PutBucketWebsite](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html)
+  《Amazon Simple Storage Service API 参考》中的 [GetBucketWebsite](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETwebsite.html)
+  《Amazon Simple Storage Service API 参考》中的 [DeleteBucketWebsite](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` 默认为 5 MB，但可以通过进行 [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 上传和下载大型数据文件的吞吐量。有关此版本改进的更多信息，请参阅[使用 适用于 C\$1\$1 的 AWS SDK v1.9 提高 Amazon S3 吞吐量](https://github.com/aws/aws-sdk-cpp/wiki/Improving-S3-Throughput-with-AWS-SDK-for-CPP-v1.9)

`S3CrtClient` 构建于 [AWS 通用运行时（CRT）库](https://docs.aws.amazon.com/sdkref/latest/guide/common-runtime.html)之上。

**注意**  
为避免因上传不完整或部分上传而产生费用，我们建议您在 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` 以分段上传的形式上传。这一点可以在程序成功运行后，通过查看调试日志来确认。

如果上传失败，底层 CRT 库中会发出 `AbortMultipartUpload`，以清理所有已上传的部分。但是，并非所有错误/故障都可以在内部处理（例如拔掉网线）。建议您在 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. 该日志包含类似以下内容的条目，其中为上传文件的每个部分指定了 `partNumber` 和 `uploadId`：

    `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`

    and 

    `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) 是一项完全托管式消息队列服务，可轻松地解耦和扩展微服务、分布式系统和无服务器应用程序。您可以使用以下示例通过 适用于 C\$1\$1 的 AWS SDK对 [Amazon SQS](https://aws.amazon.com/sqs) 进行编程。

**注意**  
本指南中仅提供了演示某些技术所需的代码，但[完整的示例代码可在上找到 GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp)。 GitHub 您可以下载单个源文件，也可以在本地克隆存储库以获取、构建和运行所有示例。

**Topics**
+ [使用 Amazon SQS 消息队列](examples-sqs-message-queues.md)
+ [发送、接收和删除 SQS 消息](examples-sqs-messages.md)
+ [为 Amazon SQS 消息队列启用长轮询](examples-sqs-long-polling.md)
+ [在 Amazon SQS 中设置可见性超时](examples-sqs-visibility-timeout.md)
+ [在 &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>
```

 **代码** 

```
    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>
```

 **代码** 

```
    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 队列的网址，请调用 SQSClient 类`GetQueueUrl`成员函数。

 **包含** 

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

 **代码** 

```
    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>

提供 SQSClient 类`DeleteQueue`成员函数的 [URL](#sqs-get-queue-url)。

 **包含** 

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

 **代码** 

```
    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)
+  [CreateQueue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html)在 Amazon 简单队列服务 API 参考中
+  [GetQueueUrl](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueUrl.html)在 Amazon 简单队列服务 API 参考中
+  [ListQueues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ListQueues.html)在 Amazon 简单队列服务 API 参考中
+  [DeleteQueues](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteQueues.html)在 Amazon 简单队列服务 API 参考中

# 发送、接收和删除 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>

您可以通过调用 SQSClient 类`SendMessage`成员函数向 Amazon SQS 队列添加一条消息。您`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>
```

 **代码** 

```
    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>
```

 **代码** 

```
    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>
```

 **代码** 

```
    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)
+  [SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html)在 Amazon 简单队列服务 API 参考中
+  [SendMessageBatch](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html)在 Amazon 简单队列服务 API 参考中
+  [ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html)在 Amazon 简单队列服务 API 参考中
+  [DeleteMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_DeleteMessage.html)在 Amazon 简单队列服务 API 参考中

# 为 Amazon SQS 消息队列启用长轮询
<a name="examples-sqs-long-polling"></a>

默认情况下，Amazon SQS 使用短轮询**，仅查询服务器的一个子集（基于加权随机分布），以确定是否有任何消息可包含在响应中。

长轮询有助于降低使用 Amazon SQS 的成本，因为在没有消息可以回复发送到 Amazon SQS 队列的 ReceiveMessage 请求时，可以减少空响应的数量，并消除虚假的空响应。您可以设置 *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 队列时启用长轮询，请在调用 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)成员函数之前对对象设置`ReceiveMessageWaitTimeSeconds`属性。

 **包含** 

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

 **代码** 

```
    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>
```

 **代码** 

```
    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 类 ReceiveMessage 成员函数的消息上设置等待时间（以秒为单位）[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)，可以在收到消息时启用长轮询。

**注意**  
你应该确保 AWS 客户端的请求超时大于最长轮询时间（20 秒），这样你的`ReceiveMessage`请求就不会在等待下一个投票事件时超时！

 **包含** 

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

 **代码** 

```
    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)
+  [CreateQueue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html)在 Amazon 简单队列服务 API 参考中
+  [ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html)在 Amazon 简单队列服务 API 参考中
+  [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)在 Amazon 简单队列服务 API 参考中

# 在 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`成员函数的 a [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>
```

 **代码** 

```
    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)
+  [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)在 Amazon 简单队列服务 API 参考中
+  [GetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html)在 Amazon 简单队列服务 API 参考中
+  [ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html)在 Amazon 简单队列服务 API 参考中
+  [ChangeMessageVisibility](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ChangeMessageVisibility.html)在 Amazon 简单队列服务 API 参考中
+  [ChangeMessageVisibilityBatch](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ChangeMessageVisibilityBatch.html)在 Amazon 简单队列服务 API 参考中

# 在 &SQS; 中使用死信队列
<a name="examples-sqs-dead-letter-queues"></a>

Amazon SQS 支持死信队列**。死信队列是一个专门接收其他队列中无法被成功处理的消息的队列。您可以在死信队列中留出和隔离这些消息以确定其处理失败的原因。

要创建死信队列，您必须先创建一个重新驱动策略**，然后在队列属性中设置该策略。

**重要**  
死信队列必须与源队列属于相同的队列类型（FIFO 或标准）。还必须使用与源队列 AWS 区域 相同 AWS 账户 的 and 来创建它。

## 先决条件
<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 中指定。要创建重新驱动策略，您可以使用 适用于 C\$1\$1 的 AWS SDK随附的 JSON 实用程序类。

这是一个示例函数，它通过为您提供死信队列的 ARN 和消息在被发送到死信队列之前可以被接收而不被处理的最大次数来创建一个重新驱动策略。

 **包含** 

```
#include <aws/core/Aws.h>
#include <aws/core/utils/json/JsonSerializer.h>
```

 **代码** 

```
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>

要完成死信队列的设置，请使用已通过 JSON redriv SQSClient e 策略为其设置`RedrivePolicy`属性的[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)对象调用类的`SetQueueAttributes`成员函数。

 **包含** 

```
#include <aws/sqs/SQSClient.h>
#include <aws/sqs/model/SetQueueAttributesRequest.h>
#include <iostream>
```

 **代码** 

```
    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)
+  [SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)在 Amazon 简单队列服务 API 参考中