AWS SDK を使用した Amazon SNS トピックのサブスクライバーの一覧表示 - AWSSDK コードサンプル

AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの 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> /// 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 の詳細については、AWS SDK for .NETAPI ListSubscriptionsリファレンスのを参照してください

C++
SDK for C++
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

//! Retrieve a list of Amazon Simple Notification Service (Amazon SNS) subscriptions. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::listSubscriptions( 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; Aws::Vector<Aws::SNS::Model::Subscription> subscriptions; do { Aws::SNS::Model::ListSubscriptionsRequest request; if (!nextToken.empty()) { request.SetNextToken(nextToken); } const Aws::SNS::Model::ListSubscriptionsOutcome outcome = snsClient.ListSubscriptions( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SNS::Model::Subscription> &newSubscriptions = outcome.GetResult().GetSubscriptions(); subscriptions.insert(subscriptions.cend(), newSubscriptions.begin(), newSubscriptions.end()); } else { std::cerr << "Error listing subscriptions " << outcome.GetError().GetMessage() << std::endl; result = false; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); if (result) { if (subscriptions.empty()) { std::cout << "No subscriptions found" << std::endl; } else { std::cout << "Subscriptions list:" << std::endl; for (auto const &subscription: subscriptions) { std::cout << " * " << subscription.GetSubscriptionArn() << std::endl; } } } return result; }
  • API の詳細については、AWS SDK for C++API ListSubscriptionsリファレンスのを参照してください

Go
SDK for Go V2
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

package main import ( "context" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" ) // SNSListSubscriptionsAPI defines the interface for the ListSubscriptions function. // We use this interface to test the function using a mocked service. type SNSListSubscriptionsAPI interface { ListSubscriptions(ctx context.Context, params *sns.ListSubscriptionsInput, optFns ...func(*sns.Options)) (*sns.ListSubscriptionsOutput, error) } // GetSubscriptions retrieves a list of your Amazon Simple Notification Service (Amazon SNS) subscriptions. // Inputs: // c is the context of the method call, which includes the AWS Region. // api is the interface that defines the method call. // input defines the input arguments to the service call. // Output: // If success, a ListSubscriptionsOutput object containing the result of the service call and nil. // Otherwise, nil and an error from the call to ListSubscriptions. func GetSubscriptions(c context.Context, api SNSListSubscriptionsAPI, input *sns.ListSubscriptionsInput) (*sns.ListSubscriptionsOutput, error) { return api.ListSubscriptions(c, input) } func main() { cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sns.NewFromConfig(cfg) input := &sns.ListSubscriptionsInput{} result, err := GetSubscriptions(context.TODO(), client, input) if err != nil { fmt.Println("Got an error retrieving the subscriptions:") fmt.Println(err) return } fmt.Println("Topic ARN") fmt.Println("Subscription ARN") fmt.Println("-------------------------") for _, s := range result.Subscriptions { fmt.Println(*s.TopicArn) fmt.Println(*s.SubscriptionArn) fmt.Println("") } }
  • API の詳細については、AWS SDK for GoAPI ListSubscriptionsリファレンスのを参照してください

Java
SDK for Java 2.x
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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 の詳細については、AWS SDK for Java 2.xAPI ListSubscriptionsリファレンスのを参照してください

JavaScript
SDK forJavaScript v3)
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

別のモジュールでクライアントを作成し、エクスポートします。

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 };

SDK モジュールとクライアントモジュールをインポートし、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();
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScriptAPI ListSubscriptionsリファレンスのを参照してください

Kotlin
SDK for Kotlin
注記

これはプレビューリリースの機能に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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 の詳細については、「AWSSDK for Kotlin API リファレンス」を参照してくださいListSubscriptions

PHP
SDK for PHP
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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 の詳細については、AWS SDK for PHPAPI ListSubscriptionsリファレンスのを参照してください

Python
SDK for Python (Boto3)
注記

他にもあります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_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 の詳細については、「AWSSDK for Python (Boto3) API リファレンス」のを参照してくださいListSubscriptions

Ruby
SDK for Ruby
注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

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__
  • 詳細については、AWS SDK for Ruby デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for RubyAPI ListSubscriptionsリファレンスのを参照してください

SAP ABAP
SDK for SAP ABAP
注記

これはデベロッパープレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があるため、本稼働環境での使用はお勧めできません。

注記

他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリでの設定と実行の方法を確認してください。

TRY. oo_result = lo_sns->listsubscriptions( ). " oo_result is returned for testing purposes. " DATA(lt_subscriptions) = oo_result->get_subscriptions( ). MESSAGE 'Retrieved list of subscribers.' TYPE 'I'. CATCH /aws1/cx_rt_generic. MESSAGE 'Unable to list subscribers.' TYPE 'E'. ENDTRY.
  • API の詳細については、「ListSubscriptionsSDK for SAP ABAP API リファレンス」の「AWSSDK for SAP ABAP API リファレンス」の