使用软件开发工具包发布到 Amazon SNS 主题 Amazon - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

使用软件开发工具包发布到 Amazon SNS 主题 Amazon

以下代码示例演示了如何将消息发布到 Amazon SNS 主题。

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

.NET
Amazon SDK for .NET
注意

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

向主题发布消息。

using System; using System.Threading.Tasks; using Amazon.SimpleNotificationService; using Amazon.SimpleNotificationService.Model; /// <summary> /// This example publishes a message to an Amazon Simple Notification /// Service (Amazon SNS) topic. /// </summary> public class PublishToSNSTopic { public static async Task Main() { string topicArn = "arn:aws:sns:us-east-2:000000000000:ExampleSNSTopic"; string messageText = "This is an example message to publish to the ExampleSNSTopic."; IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient(); await PublishToTopicAsync(client, topicArn, messageText); } /// <summary> /// Publishes a message to an Amazon SNS topic. /// </summary> /// <param name="client">The initialized client object used to publish /// to the Amazon SNS topic.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="messageText">The text of the message.</param> public static async Task PublishToTopicAsync( IAmazonSimpleNotificationService client, string topicArn, string messageText) { var request = new PublishRequest { TopicArn = topicArn, Message = messageText, }; var response = await client.PublishAsync(request); Console.WriteLine($"Successfully published message ID: {response.MessageId}"); } }

向主题发布带有属性、可选的重复数据删除和组 ID 的消息。

/// <summary> /// Publish a message to a topic with an attribute and optional deduplication and group IDs. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="message">The message to publish.</param> /// <param name="attributeName">The optional attribute for the message.</param> /// <param name="attributeValue">The optional attribute value for the message.</param> /// <param name="deduplicationId">The optional deduplication ID for the message.</param> /// <param name="groupId">The optional group ID for the message.</param> /// <returns>The ID of the message published.</returns> public async Task<string> PublishToTopicWithAttribute( string topicArn, string message, string? attributeName = null, string? attributeValue = null, string? deduplicationId = null, string? groupId = null) { var publishRequest = new PublishRequest() { TopicArn = topicArn, Message = message, MessageDeduplicationId = deduplicationId, MessageGroupId = groupId }; if (attributeValue != null) { // Add the string attribute if it exists. publishRequest.MessageAttributes = new Dictionary<string, MessageAttributeValue> { { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} } }; } var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest); return publishResponse.MessageId; }
  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 Publish

C++
适用于 C++ 的 SDK
注意

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

//! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic. /*! \param message: The message to publish. \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::publishToTopic(const Aws::String &message, const Aws::String &topicARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::PublishRequest request; request.SetMessage(message); request.SetTopicArn(topicARN); const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Message published successfully with id '" << outcome.GetResult().GetMessageId() << "'." << std::endl; } else { std::cerr << "Error while publishing message " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 Publish

CLI
Amazon CLI

示例 1:向主题发布消息

以下 publish 示例将指定消息发布到指定 SNS 主题。该消息来自一个文本文件,您可以在该文件中包含换行符。

aws sns publish \ --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \ --message file://message.txt

message.txt 的内容:

Hello World Second Line

输出:

{ "MessageId": "123a45b6-7890-12c3-45d6-111122223333" }

示例 2:向电话号码发布 SMS 消息

以下 publish 示例将消息 Hello world! 发布到电话号码 +1-555-555-0100

aws sns publish \ --message "Hello world!" \ --phone-number +1-555-555-0100

输出:

{ "MessageId": "123a45b6-7890-12c3-45d6-333322221111" }
  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 Publish

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 } // Publish publishes a message to an Amazon SNS topic. The message is then sent to all // subscribers. When the topic is a FIFO topic, the message must also contain a group ID // and, when ID-based deduplication is used, a deduplication ID. An optional key-value // filter attribute can be specified so that the message can be filtered according to // a filter policy. func (actor SnsActions) Publish(topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error { publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)} if groupId != "" { publishInput.MessageGroupId = aws.String(groupId) } if dedupId != "" { publishInput.MessageDeduplicationId = aws.String(dedupId) } if filterKey != "" && filterValue != "" { publishInput.MessageAttributes = map[string]types.MessageAttributeValue{ filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)}, } } _, err := actor.SnsClient.Publish(context.TODO(), &publishInput) if err != nil { log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err) } return err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 Publish

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.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; 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 PublishTopic { public static void main(String[] args) { final String usage = """ Usage: <message> <topicArn> Where: message - The message text to send. topicArn - The ARN of the topic to publish. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String topicArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTopic(snsClient, message, topicArn); snsClient.close(); } public static void pubTopic(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Publish

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 { PublishCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object * if you are using the `json` `MessageStructure`. * @param {string} topicArn - The ARN of the topic to which you would like to publish. */ export const publish = async ( message = "Hello from SNS!", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( new PublishCommand({ Message: message, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };
Kotlin
适用于 Kotlin 的 SDK
注意

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

suspend fun pubTopic(topicArnVal: String, messageVal: String) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 Publish

PHP
适用于 PHP 的 SDK
注意

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

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Sends a message to an Amazon SNS topic. * * 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' ]); $message = 'This message is sent from a Amazon SNS code sample.'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->publish([ 'Message' => $message, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Python
适用于 Python (Boto3) 的 SDK
注意

还有更多相关信息 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 publish_message(topic, message, attributes): """ Publishes a message, with attributes, to a topic. Subscriptions can be filtered based on message attributes so that a subscription receives messages only when specified attributes are present. :param topic: The topic to publish to. :param message: The message to publish. :param attributes: The key-value attributes to attach to the message. Values must be either `str` or `bytes`. :return: The ID of the message. """ try: att_dict = {} for key, value in attributes.items(): if isinstance(value, str): att_dict[key] = {"DataType": "String", "StringValue": value} elif isinstance(value, bytes): att_dict[key] = {"DataType": "Binary", "BinaryValue": value} response = topic.publish(Message=message, MessageAttributes=att_dict) message_id = response["MessageId"] logger.info( "Published message with attributes %s to topic %s.", attributes, topic.arn, ) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id

发布基于订阅者的协议采取不同形式的消息。

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 publish_multi_message( topic, subject, default_message, sms_message, email_message ): """ Publishes a multi-format message to a topic. A multi-format message takes different forms based on the protocol of the subscriber. For example, an SMS subscriber might receive a short version of the message while an email subscriber could receive a longer version. :param topic: The topic to publish to. :param subject: The subject of the message. :param default_message: The default version of the message. This version is sent to subscribers that have protocols that are not otherwise specified in the structured message. :param sms_message: The version of the message sent to SMS subscribers. :param email_message: The version of the message sent to email subscribers. :return: The ID of the message. """ try: message = { "default": default_message, "sms": sms_message, "email": email_message, } response = topic.publish( Message=json.dumps(message), Subject=subject, MessageStructure="json" ) message_id = response["MessageId"] logger.info("Published multi-format message to topic %s.", topic.arn) except ClientError: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise else: return message_id
  • 有关 API 详细信息,请参阅《适用于 Python (Boto3) 的Amazon SDK API 参考》中的 Publish

Ruby
适用于 Ruby 的 SDK
注意

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

# Service class for sending messages using Amazon Simple Notification Service (SNS) class SnsMessageSender # Initializes the SnsMessageSender 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 # Sends a message to a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param message [String] The message to send # @return [Boolean] true if message was successfully sent, false otherwise def send_message(topic_arn, message) @sns_client.publish(topic_arn: topic_arn, message: message) @logger.info("Message sent successfully to #{topic_arn}.") true rescue Aws::SNS::Errors::ServiceError => e @logger.error("Error while sending the message: #{e.message}") false end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = "SNS_TOPIC_ARN" # Should be replaced with a real topic ARN message = "MESSAGE" # Should be replaced with the actual message content sns_client = Aws::SNS::Client.new message_sender = SnsMessageSender.new(sns_client) @logger.info("Sending message.") unless message_sender.send_message(topic_arn, message) @logger.error("Message sending failed. Stopping program.") exit 1 end end
Rust
SDK for Rust
注意

还有更多相关信息 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 参考》中的 Publish

SAP ABAP
SDK for SAP ABAP
注意

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

TRY. oo_result = lo_sns->publish( " oo_result is returned for testing purposes. " iv_topicarn = iv_topic_arn iv_message = iv_message ). MESSAGE 'Message published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.
  • 有关 API 详细信息,请参阅适用于 SAP ABAP 的Amazon SDK 的 API 参考中的发布

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