使用 Amazon 软件开发工具包创建 Amazon SNS 主题
以下代码示例显示如何创建 Amazon SNS 主题。
- .NET
-
- Amazon SDK for .NET
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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. The example was created /// using the AWS SDK for .NET version 3.7 and .NET Core 5.0. /// </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; } }
-
有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 CreateTopic。
-
- C++
-
- SDK for C++
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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);
-
有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 CreateTopic。
-
- Go
-
- SDK for Go V2
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 -
有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 CreateTopic
。
-
- Java
-
- SDK for Java 2.x
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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 ""; }
-
有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 CreateTopic。
-
- JavaScript
-
- SDK for JavaScript V3
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 在单独的模块中创建客户端并将其导出。
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();
-
有关更多信息,请参阅 Amazon SDK for JavaScript 开发人员指南。
-
有关 API 详细信息,请参阅 Amazon SDK for JavaScript API 参考中的 CreateTopic。
-
- Kotlin
-
- SDK for Kotlin
-
注意 这是适用于预览版中功能的预发行文档。本文档随时可能更改。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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() } }
-
有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 CreateTopic
。
-
- PHP
-
- SDK for PHP
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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()); }
-
有关更多信息,请参阅 Amazon SDK for PHP 开发人员指南。
-
有关 API 详细信息,请参阅 Amazon SDK for PHP API 参考中的 CreateTopic。
-
- Python
-
- 适用于 Python (Boto3) 的 SDK
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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
-
有关 API 详细信息,请参阅《适用于 Python (Boto3) 的 Amazon SDK API 参考》中的 CreateTopic。
-
- Ruby
-
- SDK for Ruby
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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__
-
有关更多信息,请参阅 Amazon SDK for Ruby 开发人员指南。
-
有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 CreateTopic。
-
- Rust
-
- SDK for Rust
-
注意 本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 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 详细信息,请参阅 Amazon SDK for Rust API 参考中的 CreateTopic
。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 Amazon SNS 与 Amazon 开发工具包结合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。