ListTopics与 S Amazon DK 或命令行工具配合使用 - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

ListTopics与 S Amazon DK 或命令行工具配合使用

以下代码示例演示如何使用 ListTopics

.NET
Amazon SDK for .NET
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// Lists the Amazon Simple Notification Service (Amazon SNS) /// topics for the current account. /// </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。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

//! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) topics. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::listTopics(const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::String nextToken; // Next token is used to handle a paginated response. bool result = true; do { Aws::SNS::Model::ListTopicsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListTopicsOutcome outcome = snsClient.ListTopics( request); if (outcome.IsSuccess()) { std::cout << "Topics list:" << std::endl; for (auto const &topic: outcome.GetResult().GetTopics()) { std::cout << " * " << topic.GetTopicArn() << std::endl; } } else { std::cerr << "Error listing topics " << outcome.GetError().GetMessage() << std::endl; result = false; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); return result; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考ListTopics中的。

CLI
Amazon CLI

列出 SNS 主题

以下list-topics示例列出了您 Amazon 账户中的所有 SNS 主题。

aws sns list-topics

输出:

{ "Topics": [ { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" } ] }
  • 有关 API 的详细信息,请参阅Amazon CLI 命令参考ListTopics中的。

Go
适用于 Go V2 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Notification Service // (Amazon SNS) client and list the topics in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { sdkConfig, err := config.LoadDefaultConfig(context.TODO()) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } snsClient := sns.NewFromConfig(sdkConfig) fmt.Println("Let's list the topics for your account.") var topics []types.Topic paginator := sns.NewListTopicsPaginator(snsClient, &sns.ListTopicsInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(context.TODO()) if err != nil { log.Printf("Couldn't get topics. Here's why: %v\n", err) break } else { topics = append(topics, output.Topics...) } } if len(topics) == 0 { fmt.Println("You don't have any topics!") } else { for _, topic := range topics { fmt.Printf("\t%v\n", *topic.TopicArn) } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Go API 参考ListTopics中的。

Java
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListTopicsRequest; import software.amazon.awssdk.services.sns.model.ListTopicsResponse; 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 ListTopics { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSTopics(snsClient); snsClient.close(); } 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
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

在单独的模块中创建客户端并将其导出。

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 { ListTopicsCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const listTopics = async () => { const response = await snsClient.send(new ListTopicsCommand({})); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ] // } return response; };
Kotlin
适用于 Kotlin 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅适用ListTopics于 K otlin 的Amazon SDK API 参考

PHP
适用于 PHP 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * 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
SDK for Python (Boto3)
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 的详细信息,请参阅适用ListTopicsPython 的Amazon SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 # Example usage: run_me if $PROGRAM_NAME == __FILE__
Rust
适用于 Rust 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

async fn show_topics(client: &Client) -> Result<(), Error> { let resp = client.list_topics().send().await?; println!("Topic ARNs:"); for topic in resp.topics() { println!("{}", topic.topic_arn().unwrap_or_default()); } Ok(()) }
  • 有关 API 的详细信息,请参阅适用ListTopicsRust 的Amazon SDK API 参考

SAP ABAP
SDK for SAP ABAP
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

TRY. oo_result = lo_sns->listtopics( ). " oo_result is returned for testing purposes. " DATA(lt_topics) = oo_result->get_topics( ). MESSAGE 'Retrieved list of topics.' TYPE 'I'. CATCH /aws1/cx_rt_generic. MESSAGE 'Unable to list topics.' TYPE 'E'. ENDTRY.
  • 有关 API 的详细信息,请参阅适用ListTopics于 S AP 的Amazon SDK ABAP API 参考

有关 S Amazon DK 开发者指南和代码示例的完整列表,请参阅将 Amazon SNS 与 Amazon 开发工具包结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。