使用 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> /// This example will retrieve a list of the existing Amazon Simple /// Notification Service (Amazon SNS) subscriptions. The example was /// created using the AWS SDK for .NET 3.7 and .NET Core 5.0. /// </summary> public class ListSubscriptions { public static async Task Main() { IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); var subscriptions = await GetSubscriptionsListAsync(client); DisplaySubscriptionList(subscriptions); } /// <summary> /// Gets a list of the existing Amazon SNS subscriptions. /// </summary> /// <param name="client">The initialized Amazon SNS client object used /// to obtain the list of subscriptions.</param> /// <returns>A List containing information about each subscription.</returns> public static async Task<List<Subscription>> GetSubscriptionsListAsync(IAmazonSimpleNotificationService client) { var response = await client.ListSubscriptionsAsync(); return response.Subscriptions; } /// <summary> /// Display a list of Amazon SNS subscription information. /// </summary> /// <param name="subscriptionList">A list containing details for existing /// Amazon SNS subscriptions.</param> public static void DisplaySubscriptionList(List<Subscription> subscriptionList) { foreach (var subscription in subscriptionList) { Console.WriteLine($"Owner: {subscription.Owner}"); Console.WriteLine($"Subscription ARN: {subscription.SubscriptionArn}"); Console.WriteLine($"Topic ARN: {subscription.TopicArn}"); Console.WriteLine($"Endpoint: {subscription.Endpoint}"); Console.WriteLine($"Protocol: {subscription.Protocol}"); Console.WriteLine(); } } }
-
有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 ListSubscriptions。
-
- C++
-
- SDK for C++
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::SNS::Model::ListSubscriptionsRequest ls_req; auto ls_out = sns.ListSubscriptions(ls_req); if (ls_out.IsSuccess()) { std::cout << "Subscriptions list:" << std::endl; for (auto const& subscription : ls_out.GetResult().GetSubscriptions()) { std::cout << " * " << subscription.GetSubscriptionArn() << std::endl; } } else { std::cout << "Error listing subscriptions " << ls_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
-
有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 ListSubscriptions。
-
- Go
-
- SDK for Go V2
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 -
有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 ListSubscriptions
。
-
- Java
-
- SDK for Java 2.x
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 public static void listSNSSubscriptions( SnsClient snsClient) { try { ListSubscriptionsRequest request = ListSubscriptionsRequest.builder() .build(); ListSubscriptionsResponse result = snsClient.listSubscriptions(request); System.out.println(result.subscriptions()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
-
有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 ListSubscriptions。
-
- 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 {ListSubscriptionsByTopicCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters const params = { TopicArn: "TOPIC_ARN" }; //TOPIC_ARN const run = async () => { try { const data = await snsClient.send(new ListSubscriptionsByTopicCommand(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 参考中的 ListSubscriptions。
-
- Kotlin
-
- SDK for Kotlin
-
注意 这是适用于预览版中功能的预发行文档。本文档随时可能更改。
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 suspend fun listSNSSubscriptions() { SnsClient { region = "us-east-1" }.use { snsClient -> val response = snsClient.listSubscriptions(ListSubscriptionsRequest {}) response.subscriptions?.forEach { sub -> println("Sub ARN is ${sub.subscriptionArn}") println("Sub protocol is ${sub.protocol}") } } }
-
有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 ListSubscriptions
。
-
- PHP
-
- SDK for PHP
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * Returns a list of Amazon SNS subscriptions in 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' ]); try { $result = $SnSclient->listSubscriptions([ ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
-
有关 API 详细信息,请参阅 Amazon SDK for PHP API 参考中的 ListSubscriptions。
-
- 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_subscriptions(self, topic=None): """ Lists subscriptions for the current account, optionally limited to a specific topic. :param topic: When specified, only subscriptions to this topic are returned. :return: An iterator that yields the subscriptions. """ try: if topic is None: subs_iter = self.sns_resource.subscriptions.all() else: subs_iter = topic.subscriptions.all() logger.info("Got subscriptions.") except ClientError: logger.exception("Couldn't get subscriptions.") raise else: return subs_iter
-
有关 API 详细信息,请参阅《适用于 Python (Boto3) 的 Amazon SDK API 参考》中的 ListSubscriptions。
-
- Ruby
-
- SDK for Ruby
-
提示 要了解如何设置和运行此示例,请参阅 GitHub
。 require 'aws-sdk-sns' # v2: require 'aws-sdk' def show_subscriptions?(sns_client, topic_arn) topic = sns_client.topic(topic_arn) topic.subscriptions.each do |s| puts s.attributes['Endpoint'] end rescue StandardError => e puts "Error while sending the message: #{e.message}" end def run_me topic_arn = 'SNS_TOPIC_ARN' region = 'REGION' sns_client = Aws::SNS::Resource.new(region: region) puts "Listing subscriptions to the topic." if show_subscriptions?(sns_client, topic_arn) else puts 'There was an error. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__
-
有关更多信息,请参阅 Amazon SDK for Ruby 开发人员指南。
-
有关 API 详细信息,请参阅 Amazon SDK for Ruby API 参考中的 ListSubscriptions。
-
有关 Amazon 软件开发工具包开发人员指南和代码示例的完整列表,请参阅 将 Amazon SNS 与 Amazon 开发工具包结合使用。本主题还包括有关入门的信息以及有关先前的软件开发工具包版本的详细信息。