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

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

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

以下代码示例显示了如何使用Subscribe

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

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

通过电子邮件地址订阅主题。

/// <summary> /// Creates a new subscription to a topic. /// </summary> /// <param name="client">The initialized Amazon SNS client object, used /// to create an Amazon SNS subscription.</param> /// <param name="topicArn">The ARN of the topic to subscribe to.</param> /// <returns>A SubscribeResponse object which includes the subscription /// ARN for the new subscription.</returns> public static async Task<SubscribeResponse> TopicSubscribeAsync( IAmazonSimpleNotificationService client, string topicArn) { SubscribeRequest request = new SubscribeRequest() { TopicArn = topicArn, ReturnSubscriptionArn = true, Protocol = "email", Endpoint = "recipient@example.com", }; var response = await client.SubscribeAsync(request); return response; }

使用可选筛选条件为队列订阅主题。

/// <summary> /// Subscribe a queue to a topic with optional filters. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <returns>The ARN of the new subscription.</returns> public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn) { var subscribeRequest = new SubscribeRequest() { TopicArn = topicArn, Protocol = "sqs", Endpoint = queueArn }; if (!string.IsNullOrEmpty(filterPolicy)) { subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } }; } var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest); return subscribeResponse.SubscriptionArn; }
  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 Subscribe

C++
SDK for C++
注意

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

通过电子邮件地址订阅主题。

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an email address. /*! \param topicARN: An SNS topic Amazon Resource Name (ARN). \param emailAddress: An email address. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeEmail(const Aws::String &topicARN, const Aws::String &emailAddress, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("email"); request.SetEndpoint(emailAddress); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }

为移动应用程序订阅主题。

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to a mobile app. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param endpointARN: The ARN for a mobile app or device endpoint. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeApp(const Aws::String &topicARN, const Aws::String &endpointARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("application"); request.SetEndpoint(endpointARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }

为主题订阅 Lambda 函数。

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param lambdaFunctionARN: The ARN for an AWS Lambda function. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN, const Aws::String &lambdaFunctionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("lambda"); request.SetEndpoint(lambdaFunctionARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }

为 SQS 队列订阅主题。

Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; }

使用过滤器订阅主题。

static const Aws::String TONE_ATTRIBUTE("tone"); static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious", "sincere"}; Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); if (isFifoTopic) { if (first) { std::cout << "Subscriptions to a FIFO topic can have filters." << std::endl; std::cout << "If you add a filter to this subscription, then only the filtered messages " << "will be received in the queue." << std::endl; std::cout << "For information about message filtering, " << "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html" << std::endl; std::cout << "For this example, you can filter messages by a \"" << TONE_ATTRIBUTE << "\" attribute." << std::endl; } std::ostringstream ostringstream; ostringstream << "Filter messages for \"" << queueName << "\"'s subscription to the topic \"" << topicName << "\"? (y/n)"; // Add filter if user answers yes. if (askYesNoQuestion(ostringstream.str())) { Aws::String jsonPolicy = getFilterPolicyFromUser(); if (!jsonPolicy.empty()) { filteringMessages = true; std::cout << "This is the filter policy for this subscription." << std::endl; std::cout << jsonPolicy << std::endl; request.AddAttributes("FilterPolicy", jsonPolicy); } else { std::cout << "Because you did not select any attributes, no filter " << "will be added to this subscription." << std::endl; } } } // if (isFifoTopic) Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } //! Routine that lets the user select attributes for a subscription filter policy. /*! \sa getFilterPolicyFromUser() \return Aws::String: The filter policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() { std::cout << "You can filter messages by one or more of the following \"" << TONE_ATTRIBUTE << "\" attributes." << std::endl; std::vector<Aws::String> filterSelections; int selection; do { for (size_t j = 0; j < TONES.size(); ++j) { std::cout << " " << (j + 1) << ". " << TONES[j] << std::endl; } selection = askQuestionForIntRange( "Enter a number (or enter zero to stop adding more). ", 0, static_cast<int>(TONES.size())); if (selection != 0) { const Aws::String &selectedTone(TONES[selection - 1]); // Add the tone to the selection if it is not already added. if (std::find(filterSelections.begin(), filterSelections.end(), selectedTone) == filterSelections.end()) { filterSelections.push_back(selectedTone); } } } while (selection != 0); Aws::String result; if (!filterSelections.empty()) { std::ostringstream jsonPolicyStream; jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": ["; for (size_t j = 0; j < filterSelections.size(); ++j) { jsonPolicyStream << "\"" << filterSelections[j] << "\""; if (j < filterSelections.size() - 1) { jsonPolicyStream << ","; } } jsonPolicyStream << "] }"; result = jsonPolicyStream.str(); } return result; }
  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 Subscribe

CLI
Amazon CLI

订阅主题

以下 subscribe 命令将电子邮件地址订阅到指定主题。

aws sns subscribe \ --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic \ --protocol email \ --notification-endpoint my-email@example.com

输出:

{ "SubscriptionArn": "pending confirmation" }
  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 Subscribe

Go
适用于 Go V2 的 SDK
注意

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

使用可选筛选条件为队列订阅主题。

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an // Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy // so that messages are only sent to the queue when the message has the specified attributes. func (actor SnsActions) SubscribeQueue(topicArn string, queueArn string, filterMap map[string][]string) (string, error) { var subscriptionArn string var attributes map[string]string if filterMap != nil { filterBytes, err := json.Marshal(filterMap) if err != nil { log.Printf("Couldn't create filter policy, here's why: %v\n", err) return "", err } attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(context.TODO(), &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err }
  • 有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 Subscribe

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.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeEmail { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <email> Where: topicArn - The ARN of the topic to subscribe. email - The email address to use. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String email = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subEmail(snsClient, topicArn, email); snsClient.close(); } public static void subEmail(SnsClient snsClient, String topicArn, String email) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("email") .endpoint(email) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

为 HTTP 终端节点订阅主题。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeHTTPS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <url> Where: topicArn - The ARN of the topic to subscribe. url - The HTTPS endpoint that you want to receive notifications. """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String url = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subHTTPS(snsClient, topicArn, url); snsClient.close(); } public static void subHTTPS(SnsClient snsClient, String topicArn, String url) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("https") .endpoint(url) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

为主题订阅 Lambda 函数。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeLambda { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <lambdaArn> Where: topicArn - The ARN of the topic to subscribe. lambdaArn - The ARN of an AWS Lambda function. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String lambdaArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnValue = subLambda(snsClient, topicArn, lambdaArn); System.out.println("Subscription ARN: " + arnValue); snsClient.close(); } public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("lambda") .endpoint(lambdaArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); return result.subscriptionArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 Subscribe

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 { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. * @param {string} emailAddress - The email address that is subscribed to the topic. */ export const subscribeEmail = async ( topicArn = "TOPIC_ARN", emailAddress = "usern@me.com", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "email", TopicArn: topicArn, Endpoint: emailAddress, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } };

为移动应用程序订阅主题。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created * when an application registers for notifications. */ export const subscribeApp = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "application", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

为主题订阅 Lambda 函数。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

为 SQS 队列订阅主题。

import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueue = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

使用过滤器订阅主题。

import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueueFiltered = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, Attributes: { // This subscription will only receive messages with the 'event' attribute set to 'order_placed'. FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ event: ["order_placed"], }), }, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };
Kotlin
适用于 Kotlin 的 SDK
注意

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

通过电子邮件地址订阅主题。

suspend fun subEmail(topicArnVal: String, email: String): String { val request = SubscribeRequest { protocol = "email" endpoint = email returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) return result.subscriptionArn.toString() } }

为主题订阅 Lambda 函数。

suspend fun subLambda(topicArnVal: String?, lambdaArn: String?) { val request = SubscribeRequest { protocol = "lambda" endpoint = lambdaArn returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println(" The subscription Arn is ${result.subscriptionArn}") } }
  • 有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 Unsubscribe

PHP
适用于 PHP 的 SDK
注意

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

通过电子邮件地址订阅主题。

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * 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' ]); $protocol = 'email'; $endpoint = 'sample@example.com'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }

为 HTTP 终端节点订阅主题。

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Prepares to subscribe an endpoint by sending the endpoint a confirmation message. * * 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' ]); $protocol = 'https'; $endpoint = 'https://'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->subscribe([ 'Protocol' => $protocol, 'Endpoint' => $endpoint, 'ReturnSubscriptionArn' => true, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
  • 有关 API 详细信息,请参阅 Amazon SDK for PHP API 参考中的 Subscribe

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 @staticmethod def subscribe(topic, protocol, endpoint): """ Subscribes an endpoint to the topic. Some endpoint types, such as email, must be confirmed before their subscriptions are active. When a subscription is not confirmed, its Amazon Resource Number (ARN) is set to 'PendingConfirmation'. :param topic: The topic to subscribe to. :param protocol: The protocol of the endpoint, such as 'sms' or 'email'. :param endpoint: The endpoint that receives messages, such as a phone number (in E.164 format) for SMS messages, or an email address for email messages. :return: The newly added subscription. """ try: subscription = topic.subscribe( Protocol=protocol, Endpoint=endpoint, ReturnSubscriptionArn=True ) logger.info("Subscribed %s %s to topic %s.", protocol, endpoint, topic.arn) except ClientError: logger.exception( "Couldn't subscribe %s %s to topic %s.", protocol, endpoint, topic.arn ) raise else: return subscription
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 Subscribe

Ruby
适用于 Ruby 的 SDK
注意

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

通过电子邮件地址订阅主题。

require "aws-sdk-sns" require "logger" # Represents a service for creating subscriptions in Amazon Simple Notification Service (SNS) class SubscriptionService # Initializes the SubscriptionService with an SNS client # # @param sns_client [Aws::SNS::Client] The SNS client def initialize(sns_client) @sns_client = sns_client @logger = Logger.new($stdout) end # Attempts to create a subscription to a topic # # @param topic_arn [String] The ARN of the SNS topic # @param protocol [String] The subscription protocol (e.g., email) # @param endpoint [String] The endpoint that receives the notifications (email address) # @return [Boolean] true if subscription was successfully created, false otherwise def create_subscription(topic_arn, protocol, endpoint) @sns_client.subscribe(topic_arn: topic_arn, protocol: protocol, endpoint: endpoint) @logger.info("Subscription created successfully.") true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while creating the subscription: #{e.message}") false end end # Main execution if the script is run directly if $PROGRAM_NAME == __FILE__ protocol = "email" endpoint = "EMAIL_ADDRESS" # Should be replaced with a real email address topic_arn = "TOPIC_ARN" # Should be replaced with a real topic ARN sns_client = Aws::SNS::Client.new subscription_service = SubscriptionService.new(sns_client) @logger.info("Creating the subscription.") unless subscription_service.create_subscription(topic_arn, protocol, endpoint) @logger.error("Subscription creation failed. Stopping program.") exit 1 end end
Rust
适用于 Rust 的 SDK
注意

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

通过电子邮件地址订阅主题。

async fn subscribe_and_publish( client: &Client, topic_arn: &str, email_address: &str, ) -> Result<(), Error> { println!("Receiving on topic with ARN: `{}`", topic_arn); let rsp = client .subscribe() .topic_arn(topic_arn) .protocol("email") .endpoint(email_address) .send() .await?; println!("Added a subscription: {:?}", rsp); let rsp = client .publish() .topic_arn(topic_arn) .message("hello sns!") .send() .await?; println!("Published message: {:?}", rsp); Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 Subscribe

SAP ABAP
SDK for SAP ABAP
注意

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

通过电子邮件地址订阅主题。

TRY. oo_result = lo_sns->subscribe( "oo_result is returned for testing purposes." iv_topicarn = iv_topic_arn iv_protocol = 'email' iv_endpoint = iv_email_address iv_returnsubscriptionarn = abap_true ). MESSAGE 'Email address subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY.
  • 有关 API 详细信息,请参阅适用于 SAP ABAP 的Amazon SDK 的 API 参考中的订阅

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