Amazon SNS 消息发布 - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

Amazon SNS 消息发布

创建 Amazon SNS 主题并为终端节点订阅主题后,可以将消息发布到主题。发布消息时,Amazon SNS 会尝试将消息传输给订阅的终端节点

重要

您只能将消息发布到同一 Amazon 区域中的主题和终端节点。

要使用 Amazon Web Services Management Console 将消息发布到 Amazon SNS 主题

  1. 登录 Amazon SNS 控制台

  2. 在左侧导航窗格中,选择主题

  3. Topics(主题)页上,选择一个主题,然后选择Publish message(发布主题)。

    控制台将打开 Publish message to topic(将消息发布到主题)页面。

  4. Message details(消息详细信息)部分中,执行以下操作:

    1. (可选)输入消息 Subject(主题)。

    2. 对于 FIFO topic(FIFO 主题),输入 Message group ID(消息组 ID)。同一消息组中的消息按消息的发布顺序传输。

    3. 对于 FIFO 主题,请输入 Message deduplication ID(消息重复数据删除 ID)。如果您为主题启用了 Content-based message deduplication(基于内容的消息重复数据删除)设置,则此 ID 为可选项。

    4. (可选)对于 mobile push notifications(移动推送通知),输入 Time to Live (TTL)(存活时间 (TTL))值(以秒为单位)。这是推送通知服务(如 Apple Push Notification Service (APNs) 或 Firebase Cloud Messaging (FCM))必须将消息传送至终端节点的时间。

  5. Message body (消息正文) 部分中,执行以下操作之一:

    1. 选择 Identical payload for all delivery protocols(完全相同负载用于所有交付协议),然后输入消息。

    2. 选择 Custom payload for each delivery protocol(对每个交付协议使用自定义负载),然后输入 JSON 对象定义要发送给每个协议的消息。

      有关更多信息,请参阅 使用特定于平台的负载发布

  6. Message attributes(消息属性)部分中,添加您希望 Amazon SNS 与订阅属性 FilterPolicy 相匹配的任何属性,以确定订阅的终端节点是否对发布的消息感兴趣。

    1. 对于 Type(类型),选择属性类型,例如 String.Array

      注意

      对于属性类型 String.Array,请将该数组放入方括号 ([]) 内。在该数组内,将字符串值加入双引号内。数字以及关键字 truefalsenull 无需加引号。

    2. 输入属性名称,例如 customer_interests

    3. 输入属性,例如 ["soccer", "rugby", "hockey"]

    如果属性类型是 StringString.ArrayNumber,Amazon SNS 会首先依据订阅的筛选策略(如果存在)来评估该消息属性,然后再将消息发送至该订阅。

    有关更多信息,请参阅 Amazon SNS 消息属性

  7. 选择发布消息

    消息将发布到主题,且控制台将打开主题的 Details(详细信息)页面。

使用 Amazon SDK 将消息发布到主题

要使用 Amazon 开发工具包,您必须使用您的凭证对其进行配置。有关更多信息,请参阅 Amazon 开发工具包和工具参考指南中的共享配置和凭证文件

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

.NET
Amazon SDK for .NET
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for .NET API 参考中的 Publish

C++
SDK for C++

Aws::SDKOptions options; Aws::InitAPI(options); { Aws::SNS::SNSClient sns; Aws::String message = argv[1]; Aws::String topic_arn = argv[2]; Aws::SNS::Model::PublishRequest psms_req; psms_req.SetMessage(message); psms_req.SetTopicArn(topic_arn); auto psms_out = sns.Publish(psms_req); if (psms_out.IsSuccess()) { std::cout << "Message published successfully " << std::endl; } else { std::cout << "Error while publishing message " << psms_out.GetError().GetMessage() << std::endl; } } Aws::ShutdownAPI(options);
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for C++ API 参考中的 Publish

Go
SDK for Go V2
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Go API 参考中的 Publish

Java
SDK for Java 2.x

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); } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Java 2.x API 参考中的 Publish

JavaScript
SDK for JavaScript V3

在单独的模块中创建客户端并将其导出。

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 {PublishCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters var params = { Message: "MESSAGE_TEXT", // MESSAGE_TEXT TopicArn: "TOPIC_ARN", //TOPIC_ARN }; const run = async () => { try { const data = await snsClient.send(new PublishCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

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.") } }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Kotlin API 参考中的 Publish

PHP
SDK for PHP

require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * 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
SDK for Python (Boto3)

发布包含属性的消息,以便订阅可以根据属性进行筛选。

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 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 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, text-only version of the message while an email subscriber could receive an HTML version of the message. :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
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Python (Boto3) API 参考中的 Publish

Ruby
SDK for Ruby

require 'aws-sdk-sns' # v2: require 'aws-sdk' def message_sent?(sns_client, topic_arn, message) sns_client.publish(topic_arn: topic_arn, message: message) rescue StandardError => e puts "Error while sending the message: #{e.message}" end def run_me topic_arn = 'SNS_TOPIC_ARN' region = 'REGION' message = 'MESSAGE' # The text of the message to send. sns_client = Aws::SNS::Client.new(region: region) puts "Message sending." if message_sent?(sns_client, topic_arn, message) puts 'The message was sent.' else puts 'The message was not sent. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__
Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

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(()) }
  • GitHub 中查找说明和更多代码。

  • 有关 API 详细信息,请参阅 Amazon SDK for Rust API 参考中的 Publish