Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门。创建 Amazon SNS 主题
Amazon SNS 主题是一个逻辑访问点,可充当通信通道。利用主题,您可以对多个终端节点(例如,Amazon Lambda、Amazon SQS、HTTP/S 或电子邮件地址)进行分组。
要广播使用需要其消息的多个其他服务(例如,结算和执行系统)的消息创建器系统(例如,电子商务网站)的消息,您可以为创建器系统创建主题。
第一个也是最常见的 Amazon SNS 任务是创建主题。此页面显示如何使用 Amazon Web Services Management Console、Amazon SDK for Java 以及 Amazon SDK for .NET 创建主题。
在创建过程中,您可以选择主题类型(标准或 FIFO)并命名主题。创建主题后,无法更改主题类型或名称。在创建主题期间,所有其他配置选项都是可选的,您可以稍后对其进行编辑。
请勿在主题名称中添加个人身份信息 (PII) 或其他机密或敏感信息。其他亚马逊云科技(包括 CloudWatch Logs)可以访问主题名称。主题名称不适合用于私有或敏感数据。
使用 Amazon Web Services Management Console创建主题
登录 Amazon SNS 控制台。
-
请执行下列操作之一:
在 Topics(主页)页面上,选择 Create topic(创建主题)。
-
在 Create topic(创建主题)页面上,在 Details(详细信息)部分中,执行以下操作:
-
对于 Type(类型),选择主题类型(标准或者FIFO)。
-
输入主题的名称。对于 FIFO 主题,将 .fifo 添加到名称的末尾。
-
(可选)输入主题的显示名称。
-
(可选)对于 FIFO 主题,您可以选择基于内容的消息重复数据删除以启用默认的消息重复数据删除。有关更多信息,请参阅 FIFO 主题的消息重复数据删除。
-
(可选)展开加密部分并执行以下操作。有关更多信息,请参阅 静态加密。
-
选择 Enable encryption (启用加密)。
-
指定客户主密钥 (CMK)。有关更多信息,请参阅 关键术语。
对于每个 CMK 类型,都会显示 Description (描述)、Account (账户) 和 CMK ARN。
如果您不是 CMK 的拥有者,或者您登录的账户没有 kms:ListAliases
和 kms:DescribeKey
权限,则无法在 Amazon SNS 控制台上查看有关 CMK 的信息。
要求 CMK 拥有者授予您这些权限。有关更多信息,请参阅 Amazon Key Management Service 开发人员指南中的 Amazon KMS API 权限:操作和资源参考。
-
默认情况下,Amazon SNS 的 Amazon 托管 CMK(默认)alias/aws/sns 被选择。
-
要从您的 Amazon 账户中使用已定义 CMK,请选择 Customer master key (CMK)(客户主密钥 (CMK))字段,然后从列表中选择自定义 CMK。
有关创建自定义 CMK 的说明,请参阅 Amazon Key Management Service 开发人员指南中的创建密钥
-
要从您的 Amazon 账户或另一个 Amazon 账户中使用使用自定义 CMK ARN,请将其输入到 Customer master key (CMK)(客户主密钥 (CMK))字段中。
-
(可选)默认情况下,只有主题拥有者才能发布或订阅主题。要配置其他访问权限,请展开访问策略部分。有关更多信息,请参阅 Amazon SNS 中的 Identity and Access Management 和 用于 Amazon SNS 访问控制的示例案例。
使用控制台创建主题时,默认策略使用 aws:SourceOwner
条件键。此密钥类似于 aws:SourceAccount
。
-
(可选)要配置 Amazon SNS 重试失败消息传输尝试的方式,请展开 Delivery retry policy (HTTP/S)(传输重试策略 (HTTP/S))部分。有关更多信息,请参阅 Amazon SNS 消息传输重试。
-
(可选)要配置 Amazon SNS 记录针对 CloudWatch 的消息传输的方式,请展开 Delivery status logging(传输状态日志记录)部分。有关更多信息,请参阅 Amazon SNS 消息传输状态。
-
(可选)要将元数据标签添加到主题中,请展开标签部分,输入一个键和值(可选),然后选择添加标签。有关更多信息,请参阅 Amazon SNS 主题标记。
-
选择 Create topic(创建主题)。
此时将创建主题,并且 MyTopic
页面随即显示。
主题的名称、ARN、(可选)显示名称和主题所有者的 Amazon 账户 ID 将显示在 Details(详细信息)部分中。
-
将主题 ARN 复制到剪贴板,例如:
arn:aws:sns:us-east-2:123456789012:MyTopic
使用 Amazon 开发工具包创建主题
要使用 Amazon 开发工具包,您必须使用您的凭证对其进行配置。有关更多信息,请参阅 Amazon 开发工具包和工具参考指南中的共享配置和凭证文件。
以下代码示例显示如何创建 Amazon SNS 主题。
- .NET
-
- Amazon SDK for .NET
-
/// <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;
}
- C++
-
- SDK for C++
-
Aws::SDKOptions options;
Aws::InitAPI(options);
{
Aws::String topic_name = argv[1];
Aws::SNS::SNSClient sns;
Aws::SNS::Model::CreateTopicRequest ct_req;
ct_req.SetName(topic_name);
auto ct_out = sns.CreateTopic(ct_req);
if (ct_out.IsSuccess())
{
std::cout << "Successfully created topic " << topic_name << std::endl;
}
else
{
std::cout << "Error creating topic " << topic_name << ":" <<
ct_out.GetError().GetMessage() << std::endl;
}
}
Aws::ShutdownAPI(options);
- Go
-
- Java
-
- SDK for Java 2.x
-
public static String createSNSTopic(SnsClient snsClient, String topicName ) {
CreateTopicResponse result = null;
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 "";
}
- JavaScript
-
- SDK for JavaScript V3
-
在单独的模块中创建客户端并将其导出。
import { SNSClient } from "@aws-sdk/client-sns";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create SNS service object.
const snsClient = new SNSClient({ region: REGION });
export { snsClient };
导入开发工具包和客户端模块,然后调用 API。
// Import required AWS SDK clients and commands for Node.js
import {CreateTopicCommand } from "@aws-sdk/client-sns";
import {snsClient } from "./libs/snsClient.js";
// Set the parameters
const params = { Name: "TOPIC_NAME" }; //TOPIC_NAME
const run = async () => {
try {
const data = await snsClient.send(new CreateTopicCommand(params));
console.log("Success.", data);
return data; // For unit tests.
} catch (err) {
console.log("Error", err.stack);
}
};
run();
- Kotlin
-
- SDK for Kotlin
-
这是适用于预览版中功能的预发行文档。本文档随时可能更改。
suspend fun createSNSTopic(topicName: String): String {
val request = CreateTopicRequest {
name = topicName
}
SnsClient { region = "us-east-1" }.use { snsClient ->
val result = snsClient.createTopic(request)
return result.topicArn.toString()
}
}
- PHP
-
- SDK for PHP
-
require 'vendor/autoload.php';
use Aws\Sns\SnsClient;
use Aws\Exception\AwsException;
/**
* 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());
}
- Python
-
- SDK for Python (Boto3)
-
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
- Ruby
-
- SDK for Ruby
-
require 'aws-sdk-sns' # v2: require 'aws-sdk'
def topic_created?(sns_client, topic_name)
sns_client.create_topic(name: topic_name)
rescue StandardError => e
puts "Error while creating the topic named '#{topic_name}': #{e.message}"
end
# Full example call:
def run_me
topic_name = 'TOPIC_NAME'
region = 'REGION'
sns_client = Aws::SNS::Client.new(region: region)
puts "Creating the topic '#{topic_name}'..."
if topic_created?(sns_client, topic_name)
puts 'The topic was created.'
else
puts 'The topic was not created. Stopping program.'
exit 1
end
end
run_me if $PROGRAM_NAME == __FILE__
- Rust
-
- SDK for Rust
-
本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。
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(())
}