Verwenden Sie es ListTopics mit einem AWS SDK oder CLI - AWS SDK-Codebeispiele

Weitere AWS SDK Beispiele sind im Repo AWS Doc SDK Examples GitHub verfügbar.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Verwenden Sie es ListTopics mit einem AWS SDK oder CLI

Die folgenden Codebeispiele zeigen die VerwendungListTopics.

.NET
AWS SDK for .NET
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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}"); } } }
  • APIEinzelheiten finden Sie ListTopicsunter AWS SDK for .NET APIReferenz.

C++
SDKfür C++
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

//! 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; }
  • APIEinzelheiten finden Sie ListTopicsunter AWS SDK for C++ APIReferenz.

CLI
AWS CLI

Um Ihre SNS Themen aufzulisten

Das folgende list-topics Beispiel listet alle SNS Themen in Ihrem AWS Konto auf.

aws sns list-topics

Ausgabe:

{ "Topics": [ { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" } ] }
  • APIEinzelheiten finden Sie ListTopicsin der AWS CLI Befehlsreferenz.

Go
SDKfür Go V2
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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) } } }
  • APIEinzelheiten finden Sie ListTopicsunter AWS SDK for Go APIReferenz.

Java
SDKfür Java 2.x
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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); } } }
  • APIEinzelheiten finden Sie ListTopicsunter AWS SDK for Java 2.x APIReferenz.

JavaScript
SDKfür JavaScript (v3)
Anmerkung

Es gibt noch mehr dazu GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel- einrichten und ausführen.

Erstellen Sie den Client in einem separaten Modul und exportieren Sie ihn.

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({});

Importieren Sie die Module SDK und den Client und rufen Sie die aufAPI.

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
SDKfür Kotlin
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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}") } } }
  • APIEinzelheiten finden Sie ListTopicsin der AWS SDKAPIKotlin-Referenz.

PHP
SDK für PHP
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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()); }
  • APIEinzelheiten finden Sie ListTopicsunter AWS SDK for PHP APIReferenz.

Python
SDKfür Python (Boto3)
Anmerkung

Es gibt noch mehr dazu. GitHub Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
  • APIEinzelheiten finden Sie unter ListTopicsPython (Boto3) API -Referenz.AWS SDK

Ruby
SDKfür Ruby
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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
SDKfür Rust
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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(()) }
  • APIEinzelheiten finden Sie ListTopicsin der AWS SDKAPIRust-Referenz.

SAP ABAP
SDKfür SAP ABAP
Anmerkung

Es gibt noch mehr dazu GitHub. Sie sehen das vollständige Beispiel und erfahren, wie Sie das AWS -Code-Beispiel-Repository einrichten und ausführen.

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.
  • APIEinzelheiten finden Sie ListTopicsunter AWS SDKSAPABAPAPIals Referenz.