使用 Amazon 软件开发工具包列出 Amazon SNS 主题
以下代码示例展示如何列出 Amazon SNS 主题。
- .NET
-
- Amazon SDK for .NET
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// An example to list the Amazon Simple Notification Service (Amazon SNS) /// topics for the default user account. The code was written using the /// AWS SDK for .NET 3.7 and .NET Core 5.0. /// </summary> public class ListSNSTopics { public static async Task Main() { IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await GetTopicListAsync(client); } /// <summary> /// Retrieves the list of Amazon SNS topics in groups of up to 100 /// topics. /// </summary> /// <param name="client">The initialized Amazon SNS client object used /// to retrieve the list of topics.</param> public static async Task GetTopicListAsync(IAmazonSimpleNotificationService client) { // If there are more than 100 Amazon SNS topics, the call to // ListTopicsAsync will return a value to pass to the // method to retrieve the next 100 (or less) topics. string nextToken = string.Empty; do { var response = await client.ListTopicsAsync(nextToken); DisplayTopicsList(response.Topics); nextToken = response.NextToken; } while (!string.IsNullOrEmpty(nextToken)); } /// <summary> /// Displays the list of Amazon SNS Topic ARNs. /// </summary> /// <param name="topicList">The list of Topic ARNs.</param> public static void DisplayTopicsList(List<Topic> topicList) { foreach (var topic in topicList) { Console.WriteLine($"{topic.TopicArn}"); } } }
-
有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 ListTopics。
-
- C++
-
- SDK for C++
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::SNS::Model::ListTopicsRequest lt_req; auto lt_out = sns.ListTopics(lt_req); if (lt_out.IsSuccess()) { std::cout << "Topics list:" << std::endl; for (auto const &topic : lt_out.GetResult().GetTopics()) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } else { std::cout << "Error listing topics " << lt_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
-
有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 ListTopics。
-
- Go
-
- SDK for Go V2
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 -
有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 ListTopics
。
-
- Java
-
- SDK for Java 2.x
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsRequest request = ListTopicsRequest.builder() .build(); ListTopicsResponse result = snsClient.listTopics(request); System.out.println("Status was " + result.sdkHttpResponse().statusCode() + "\n\nTopics\n\n" + result.topics()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 ListTopics。
-
- 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 {ListTopicsCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; const run = async () => { try { const data = await snsClient.send(new ListTopicsCommand({})); 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 参考中的 ListTopics。
-
- Kotlin
-
- SDK for Kotlin
-
注意 这是适用于预览版中功能的预发行文档。本文档随时可能更改。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 suspend fun listSNSTopics() { SnsClient { region = "us-east-1" }.use { snsClient -> val response = snsClient.listTopics(ListTopicsRequest { }) response.topics?.forEach { topic -> println("The topic ARN is ${topic.topicArn}") } } }
-
有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 ListTopics
。
-
- PHP
-
- SDK for PHP
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Returns a list of the requester's topics from your AWS SNS account in the region specified. * * 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' ]); try { $result = $SnSclient->listTopics([ ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
-
有关 API 详细信息,请参阅 Amazon SDK for PHP API 参考中的 ListTopics。
-
- 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 list_topics(self): """ Lists topics for the current account. :return: An iterator that yields the topics. """ try: topics_iter = self.sns_resource.topics.all() logger.info("Got topics.") except ClientError: logger.exception("Couldn't get topics.") raise else: return topics_iter
-
有关 API 详细信息,请参阅《适用于 Python (Boto3) 的 Amazon SDK API 参考》中的 ListTopics。
-
- Ruby
-
- SDK for Ruby
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 require 'aws-sdk-sns' # v2: require 'aws-sdk' def list_topics?(sns_client) sns_client.topics.each do |topic| puts topic.arn rescue StandardError => e puts "Error while listing the topics: #{e.message}" end end def run_me region = 'REGION' sns_client = Aws::SNS::Resource.new(region: region) puts "Listing the topics." if list_topics?(sns_client) else puts 'The bucket 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 参考中的 ListTopics。
-
- Rust
-
- SDK for Rust
-
注意 本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 async fn show_topics(client: &Client) -> Result<(), Error> { let resp = client.list_topics().send().await?; println!("Topic ARNs:"); for topic in resp.topics().unwrap_or_default() { println!("{}", topic.topic_arn().unwrap_or_default()); } Ok(()) }
-
有关 API 详细信息,请参阅 Amazon SDK for Rust API 参考中的 ListTopics
。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 Amazon SNS 与 Amazon 开发工具包结合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。