

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

# 创建 Amazon SNS 主题
<a name="sns-create-topic"></a>

Amazon SNS 主题是一个逻辑接入点，可充当*通信通道*。主题允许您对多个*终端节点*（例如 Amazon SQS Amazon Lambda、HTTP/S 或电子邮件地址）进行分组。

要广播与需要其消息的多个其他服务（例如，结算和执行系统）协作的消息生产者系统（例如，电子商务网站）的消息，您可以为生产者系统创建主题。

第一个也是最常见的 Amazon SNS 任务是创建主题。本页显示了如何使用 Amazon Web Services 管理控制台 适用于 Java 的 Amazon SDK、和， 适用于 .NET 的 Amazon SDK 来创建主题。

在创建过程中，您可以选择主题类型（标准或 FIFO）并命名主题。创建主题后，无法更改主题类型或名称。在创建主题期间，所有其他配置选项都是可选的，您可以稍后对其进行编辑。

**重要**  
请勿在主题名称中添加个人身份信息 (PII) 或其他机密或敏感信息。其他 Amazon Web Services 可以访问主题名称，包括 CloudWatch 日志。主题名称不适合用于私有或敏感数据。

## 要使用创建主题 Amazon Web Services 管理控制台
<a name="create-topic-aws-console"></a>

在 Amazon SNS 中创建主题为消息分发奠定了基础，使您能够发布可以扇出给多个订阅用户的消息。此步骤对于配置主题的类型、加密设置和访问策略至关重要，可确保主题符合组织的安全、合规性和运营要求。

1. 登录 [Amazon SNS 控制台](https://console.amazonaws.cn/sns/home)。

1. 请执行以下操作之一：
   + 如果 Amazon Web Services 账户 之前未在您的主题下创建过任何主题，请阅读主页上对 Amazon SNS 的描述。
   + 如果 Amazon Web Services 账户 之前已在您的下方创建过主题，请在导航面板上选择**主题**。

1. 在 **Topics**（主页）页面上，选择 **Create topic**（创建主题）。

1. 在 **Create topic**（创建主题）页面上，在 **Details**（详细信息）部分中，执行以下操作：

   1. 对于 **Type**（类型），选择主题类型（**标准**或者**FIFO**）。

   1. 输入主题的**名称**。对于 [FIFO 主题](sns-fifo-topics.md)，将 **.fifo** 添加到名称的末尾。

   1. （可选）输入主题的**显示名称**。
**重要**  
订阅电子邮件端点时，Amazon SNS 主题显示名称和发送电子邮件地址（例如 no-reply@sns.amazonaws.com）的组合字符计数不得超过 320 个 UTF-8 字符。在为 Amazon SNS 主题配置显示名称之前，您可以使用第三方编码工具验证发送地址的长度。

   1. （可选）对于 FIFO 主题，您可以选择**基于内容的消息重复数据删除**以启用默认的消息重复数据删除。有关更多信息，请参阅 [FIFO 主题的 Amazon SNS 消息重复数据删除](fifo-message-dedup.md)。

1. （可选）展开**加密**部分并执行以下操作。有关更多信息，请参阅 [使用服务器端加密保护 Amazon SNS 数据安全](sns-server-side-encryption.md)。

   1. 选择**启用加密**。

   1. 指定密 Amazon KMS 钥。有关更多信息，请参阅 [关键术语](sns-server-side-encryption.md#sse-key-terms)。

      对于每个 KMS 类型，都会显示 **Description**（描述）、**Account**（账户）和 **KMS ARN**。
**重要**  
如果您不是 KMS 的拥有者，或者您登录的账户没有 `kms:ListAliases` 和 `kms:DescribeKey` 权限，则无法在 Amazon SNS 控制台上查看有关 KMS 的信息。  
要求 KMS 的拥有者授予您这些权限。有关更多信息，请参阅《Amazon Key Management Service Developer Guide》**中的 [Amazon KMS API Permissions: Actions and Resources Reference](https://docs.amazonaws.cn/kms/latest/developerguide/kms-api-permissions-reference.html)。
      + 默认选择适用于 Amazon SNS 的 Amazon 托管 KMS**（默认）alias/aws/sns**。
**注意**  
记住以下内容：  
首次使用为主题指定适用于 Amazon SNS 的 Amazon 托管 KMS 时， Amazon KMS 会为亚马逊 SNS 创建 Amazon 托管 KMS。 Amazon Web Services 管理控制台 
或者，在启用 SSE 的情况下首次对主题使用`Publish`操作时， Amazon KMS 会为 Amazon SNS 创建 Amazon 托管 KMS。
      + 要使用 Amazon 账户中的自定义 KMS，请选择 **KMS 密钥**字段，然后从列表中选择自定义 KMS。
**注意**  
有关创建自定义密钥的说明 KMSs，请参阅《*Amazon Key Management Service 开发者指南》*中的[创建密钥](https://docs.amazonaws.cn/kms/latest/developerguide/create-keys.html)
      + 要使用来自您的 Amazon 账户或其他账户的自定义 KMS ARN，请将其输入到 **KMS 密钥**字段中。 Amazon 

1. （可选）默认情况下，只有主题拥有者才能发布或订阅主题。要配置其他访问权限，请展开**访问策略**部分。有关更多信息，请参阅 [Amazon SNS 中的 Identity and Access Management](security-iam.md)和[用于 Amazon SNS 访问控制的示例案例](sns-access-policy-use-cases.md)。
**注意**  
使用控制台创建主题时，默认策略使用 `aws:SourceOwner` 条件键。此密钥类似于。`aws:SourceAccount`

1. （可选）要配置 Amazon SNS 重试失败消息传输尝试的方式，请展开 **Delivery retry policy (HTTP/S)**（传输重试策略 (HTTP/S)）部分。有关更多信息，请参阅 [Amazon SNS 消息传输重试](sns-message-delivery-retries.md)。

1. （可选）要配置 Amazon SNS 如何记录向其发送的消息 CloudWatch，请展开**传送状态记录部分**。有关更多信息，请参阅 [Amazon SNS 消息传输状态](sns-topic-attributes.md)。

1. （可选）要将元数据标签添加到主题中，请展开**标签**部分，输入一个**键**和**值**（可选），然后选择**添加标签**。有关更多信息，请参阅 [Amazon SNS 主题标记](sns-tags.md)。

1. 选择**创建主题**。

   主题已创建并显示***MyTopic***页面。

   主题的**名称**、**ARN**、（可选）**显示名称**和**主题所有者的** Amazon 账户 ID 显示在**详细信息**部分中。

1. 将主题 ARN 复制到剪贴板，例如：

   ```
   arn:aws:sns:us-east-2:123456789012:MyTopic
   ```

## 使用 Amazon SDK 创建主题
<a name="create-topic-aws-sdks"></a>

要使用 S Amazon DK，必须使用您的凭据对其进行配置。有关更多信息，请参阅[《工具参考指南》和《*工具参考指南》中的共享配置Amazon SDKs 和*凭据文件](https://docs.amazonaws.cn/sdkref/latest/guide/creds-config-files.html)。

以下代码示例演示如何使用 `CreateTopic`。

------
#### [ .NET ]

**适用于 .NET 的 Amazon SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)中查找完整示例，了解如何进行设置和运行。
使用特定的名称创建主题。  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example shows how to use Amazon Simple Notification Service
    /// (Amazon SNS) to add a new Amazon SNS topic.
    /// </summary>
    public class CreateSNSTopic
    {
        public static async Task Main()
        {
            string topicName = "ExampleSNSTopic";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            var topicArn = await CreateSNSTopicAsync(client, topicName);
            Console.WriteLine($"New topic ARN: {topicArn}");
        }

        /// <summary>
        /// Creates a new SNS topic using the supplied topic name.
        /// </summary>
        /// <param name="client">The initialized SNS client object used to
        /// create the new topic.</param>
        /// <param name="topicName">A string representing the topic name.</param>
        /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
        public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
        {
            var request = new CreateTopicRequest
            {
                Name = topicName,
            };

            var response = await client.CreateTopicAsync(request);

            return response.TopicArn;
        }
    }
```
创建一个包含名称以及特定 FIFO 和重复数据消除属性的新主题。  

```
    /// <summary>
    /// Create a new topic with a name and specific FIFO and de-duplication attributes.
    /// </summary>
    /// <param name="topicName">The name for the topic.</param>
    /// <param name="useFifoTopic">True to use a FIFO topic.</param>
    /// <param name="useContentBasedDeduplication">True to use content-based de-duplication.</param>
    /// <returns>The ARN of the new topic.</returns>
    public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication)
    {
        var createTopicRequest = new CreateTopicRequest()
        {
            Name = topicName,
        };

        if (useFifoTopic)
        {
            // Update the name if it is not correct for a FIFO topic.
            if (!topicName.EndsWith(".fifo"))
            {
                createTopicRequest.Name = topicName + ".fifo";
            }

            // Add the attributes from the method parameters.
            createTopicRequest.Attributes = new Dictionary<string, string>
            {
                { "FifoTopic", "true" }
            };
            if (useContentBasedDeduplication)
            {
                createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true");
            }
        }

        var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest);
        return createResponse.TopicArn;
    }
```
+  有关 API 的详细信息，请参阅 *适用于 .NET 的 Amazon SDK API 参考[CreateTopic](https://docs.amazonaws.cn/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)*中的。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicName: An Amazon SNS topic name.
  \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
                              Aws::String &topicARNResult,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::CreateTopicRequest request;
    request.SetName(topicName);

    const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);

    if (outcome.IsSuccess()) {
        topicARNResult = outcome.GetResult().GetTopicArn();
        std::cout << "Successfully created an Amazon SNS topic " << topicName
                  << " with topic ARN '" << topicARNResult
                  << "'." << std::endl;

    }
    else {
        std::cerr << "Error creating topic " << topicName << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
        topicARNResult.clear();
    }

    return outcome.IsSuccess();
}
```
+  有关 API 的详细信息，请参阅 *适用于 C\$1\$1 的 Amazon SDK API 参考[CreateTopic](https://docs.amazonaws.cn/goto/SdkForCpp/sns-2010-03-31/CreateTopic)*中的。

------
#### [ CLI ]

**Amazon CLI**  
**创建 SNS 主题**  
以下 `create-topic` 示例将创建名为 `my-topic` 的 SNS 主题。  

```
aws sns create-topic \
    --name my-topic
```
输出：  

```
{
    "ResponseMetadata": {
        "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83"
    },
    "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
}
```
有关更多信息，请参阅[《 Amazon 命令行界面用户指南》中的在 Amazon SQS 和 Amazon SNS 中使用](https://docs.amazonaws.cn/cli/latest/userguide/cli-sqs-queue-sns-topic.html)*命令Amazon 行*界面。  
+  有关 API 的详细信息，请参阅*Amazon CLI 命令参考[CreateTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/create-topic.html)*中的。

------
#### [ Go ]

**适用于 Go 的 SDK V2**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
	SnsClient *sns.Client
}



// CreateTopic creates an Amazon SNS topic with the specified name. You can optionally
// specify that the topic is created as a FIFO topic and whether it uses content-based
// deduplication instead of ID-based deduplication.
func (actor SnsActions) CreateTopic(ctx context.Context, topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) {
	var topicArn string
	topicAttributes := map[string]string{}
	if isFifoTopic {
		topicAttributes["FifoTopic"] = "true"
	}
	if contentBasedDeduplication {
		topicAttributes["ContentBasedDeduplication"] = "true"
	}
	topic, err := actor.SnsClient.CreateTopic(ctx, &sns.CreateTopicInput{
		Name:       aws.String(topicName),
		Attributes: topicAttributes,
	})
	if err != nil {
		log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err)
	} else {
		topicArn = *topic.TopicArn
	}

	return topicArn, err
}
```
+  有关 API 的详细信息，请参阅 *适用于 Go 的 Amazon SDK API 参考[CreateTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)*中的。

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

**适用于 Java 的 SDK 2.x**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * Before running this Java V2 code example, set up your development
 * environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class CreateTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicName>

                Where:
                   topicName - The name of the topic to create (for example, mytopic).

                """;

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

        String topicName = args[0];
        System.out.println("Creating a topic with name: " + topicName);
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String arnVal = createSNSTopic(snsClient, topicName);
        System.out.println("The topic ARN is" + arnVal);
        snsClient.close();
    }

    public static String createSNSTopic(SnsClient snsClient, String topicName) {
        CreateTopicResponse result;
        try {
            CreateTopicRequest request = CreateTopicRequest.builder()
                    .name(topicName)
                    .build();

            result = snsClient.createTopic(request);
            return result.topicArn();

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
        return "";
    }
}
```
+  有关 API 的详细信息，请参阅 *Amazon SDK for Java 2.x API 参考[CreateTopic](https://docs.amazonaws.cn/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)*中的。

------
#### [ JavaScript ]

**适用于 JavaScript (v3) 的软件开发工具包**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples) 中查找完整示例，了解如何进行设置和运行。
在单独的模块中创建客户端并将其导出。  

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```
导入 SDK 和客户端模块，然后调用 API。  

```
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicName - The name of the topic to create.
 */
export const createTopic = async (topicName = "TOPIC_NAME") => {
  const response = await snsClient.send(
    new CreateTopicCommand({ Name: topicName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
  // }
  return response;
};
```
+  有关更多信息，请参阅[《适用于 JavaScript 的 Amazon SDK Developer Guide》](https://docs.amazonaws.cn/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-createtopic)。
+  有关 API 的详细信息，请参阅 *适用于 JavaScript 的 Amazon SDK API 参考[CreateTopic](https://docs.amazonaws.cn/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)*中的。

------
#### [ Kotlin ]

**适用于 Kotlin 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
suspend fun createSNSTopic(topicName: String): String {
    val request =
        CreateTopicRequest {
            name = topicName
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.createTopic(request)
        return result.topicArn.toString()
    }
}
```
+  有关 API 的详细信息，请参阅适用[CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)于 K *otlin 的Amazon SDK API 参考*。

------
#### [ PHP ]

**适用于 PHP 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Create a Simple Notification Service topics in your AWS account at the requested region.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topicname = 'myTopic';

try {
    $result = $SnSclient->createTopic([
        'Name' => $topicname,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  有关更多信息，请参阅《适用于 PHP 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic](https://docs.amazonaws.cn/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic)。
+  有关 API 的详细信息，请参阅 *适用于 PHP 的 Amazon SDK API 参考[CreateTopic](https://docs.amazonaws.cn/goto/SdkForPHPV3/sns-2010-03-31/CreateTopic)*中的。

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    def create_topic(self, name):
        """
        Creates a notification topic.

        :param name: The name of the topic to create.
        :return: The newly created topic.
        """
        try:
            topic = self.sns_resource.create_topic(Name=name)
            logger.info("Created topic %s with ARN %s.", name, topic.arn)
        except ClientError:
            logger.exception("Couldn't create topic %s.", name)
            raise
        else:
            return topic
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise
```
+  有关 API 的详细信息，请参阅适用[CreateTopic](https://docs.amazonaws.cn/goto/boto3/sns-2010-03-31/CreateTopic)于 *Python 的Amazon SDK (Boto3) API 参考*。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic.
class SNSTopicCreator
  # Initializes an SNS client.
  #
  # Utilizes the default AWS configuration for region and credentials.
  def initialize
    @sns_client = Aws::SNS::Client.new
  end

  # Attempts to create an SNS topic with the specified name.
  #
  # @param topic_name [String] The name of the SNS topic to create.
  # @return [Boolean] true if the topic was successfully created, false otherwise.
  def create_topic(topic_name)
    @sns_client.create_topic(name: topic_name)
    puts "The topic '#{topic_name}' was successfully created."
    true
  rescue Aws::SNS::Errors::ServiceError => e
    # Handles SNS service errors gracefully.
    puts "Error while creating the topic named '#{topic_name}': #{e.message}"
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_name = 'YourTopicName' # Replace with your topic name
  sns_topic_creator = SNSTopicCreator.new

  puts "Creating the topic '#{topic_name}'..."
  unless sns_topic_creator.create_topic(topic_name)
    puts 'The topic was not created. Stopping program.'
    exit 1
  end
end
```
+  有关更多信息，请参阅《适用于 Ruby 的 Amazon SDK 开发人员指南》[https://docs.amazonaws.cn/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html](https://docs.amazonaws.cn/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html)。
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 Amazon SDK API 参考[CreateTopic](https://docs.amazonaws.cn/goto/SdkForRubyV3/sns-2010-03-31/CreateTopic)*中的。

------
#### [ Rust ]

**适用于 Rust 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> {
    let resp = client.create_topic().name(topic_name).send().await?;

    println!(
        "Created topic with ARN: {}",
        resp.topic_arn().unwrap_or_default()
    );

    Ok(())
}
```
+  有关 API 的详细信息，请参阅适用[CreateTopic](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)于 *Rust 的Amazon SDK API 参考*。

------
#### [ SAP ABAP ]

**适用于 SAP ABAP 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    TRY.
        oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. "
        MESSAGE 'SNS topic created' TYPE 'I'.
      CATCH /aws1/cx_snstopiclimitexcdex.
        MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'.
    ENDTRY.
```
+  有关 API 的详细信息，请参阅适用[CreateTopic](https://docs.amazonaws.cn/sdk-for-sap-abap/v1/api/latest/index.html)于 S *AP 的Amazon SDK ABAP API 参考*。

------
#### [ Swift ]

**适用于 Swift 的 SDK**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(name: name)
        )

        guard let arn = output.topicArn else {
            print("No topic ARN returned by Amazon SNS.")
            return
        }
```
+  如需了解 API 的详细信息，请参阅适用[CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:))于 S *wift 的Amazon SDK API 参考*。

------