使用 AWS SDK 列出 Amazon SNS 主題 - AWSSDK 程式碼範例

AWS文件 AWS SDK 範例 GitHub 存放庫中提供了更多 SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用 AWS SDK 列出 Amazon SNS 主題

下列程式碼範例示範如何列出 Amazon SNS 主題。

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for .NETAPI 參考ListTopics中的。

C++
適用於 C++ 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

//! 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 詳細資訊,請參閱 AWS SDK for C++API 參考ListTopics中的。

CLI
AWS CLI

列出您的 SNS 主題

下列 list-topics 範例會列出您 AWS 帳戶中的所有 SNS 主題。

aws sns list-topics

輸出:

{ "Topics": [ { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" } ] }
  • 如需 API 詳細資訊,請參閱AWS CLI命令參考ListTopics中的。

Go
SDK for Go V2
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for GoAPI 參考ListTopics中的。

Java
適用於 Java 2.x 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for Java 2.xAPI 參考ListTopics中的。

JavaScript
適用於 JavaScript (v3) 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

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。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 的詳細信息,請參閱 AWSSDK ListTopics中的 Kotlin API 參考。

PHP
適用於 PHP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWS SDK for PHPAPI 參考ListTopics中的。

Python
適用於 Python (Boto3) 的 SDK
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 的詳細資訊,請參閱AWS開發套件ListTopics中的 Python (博托 3) API 參考。

Ruby
適用於 Ruby 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

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。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 的詳細資訊,請參閱 AWSSDK ListTopics中的 Rust API 參考資料。

SAP ABAP
適用於 SAP ABAP 的開發套件
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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 詳細資訊,請參閱 AWSSDK ListTopics中的 SAP ABAP API 參考資料。