亚马逊SNS是AWS推出的消息通知服务,包含发布/订阅、短信和移动推送等功能,适用于A2A和A2P消息传送的完全托管的Pub/Sub服务。本文主要介绍AWS SNS的主要功能、原理和创建教程。
一、亚马逊SNS是什么
亚马逊SNS(Amazon SNS)是一项简便的通知服务,通过发布者与订阅者(也称为生产者和消费者)之间提供消息传递。发布者通过将消息发送至主题,与订阅者进行异步交流。主题作为一个逻辑访问点和通信通道,允许客户使用支持的终端节点类型订阅亚马逊SNS主题,并接收已发布的消息。这些终端节点包括Amazon Data Firehose、SQS、AWSLambda、HTTP、电子邮件、移动推送通知和短信(SMS)。
亚马逊SNS目前提供每月一百万个免费请求,点击进入官网免费试用。
(1)应用程序间消息
应用程序间消息支持多种订阅者,例如Amazon Data Firehose交付流、Lambda函数、亚马逊SQS队列、HTTP/S终端节点及AWS事件分叉管道。
(2)应用程序与个人通知
应用程序与个人通知功能向订阅者提供用户通知,比如移动应用程序、移动电话号码和电子邮件地址。
(3)标准与FIFO主题
使用FIFO主题可确保消息的严格顺序、定义消息组并防止消息重复。可以同时使用FIFO和标准队列来订阅FIFO主题。如果消息传输的顺序和可能的重复并不重要,建议使用标准主题。所有支持的传输协议均可订阅标准主题。
(4)消息持久性
亚马逊SNS通过多种策略协作提供消息的持久性:
- 已发布的消息会存储在多个地理位置分离的服务器和数据中心之间;
- 如果订阅的终端节点不可用,亚马逊SNS将执行传输重试策略;
- 可以创建死信队列,以保留在传输重试策略结束前未能交付的消息。
(5)消息归档、重播与分析
亚马逊SNS提供多种方式来存档消息,可以将Firehose传送流订阅到SNS主题,从而将通知发送到分析端点,例如亚马逊简单存储服务(Amazon S3)存储桶、Amazon Redshift表等。此外,SNSFIFO主题支持消息的归档和重播,允许主题所有者在其主题中存储(或归档)消息,并允许订阅者检索(或重播)这些归档消息。
(6)消息属性
消息属性允许提供与消息相关的任意元数据,便于进行更灵活的信息处理。
(7)消息筛选
默认情况下,每个订阅者会接收到发布到该主题的每条消息,如果订阅者仅希望接收部分消息,则可以为其主题订阅分配筛选策略。订阅者可以定义筛选策略的范围,以启用基于有效负载或属性的筛选。
默认的筛选策略范围为消息属性(Message Attributes),当传入消息属性与筛选策略属性匹配时,消息将传输到订阅的终端节点,否则消息将被过滤掉。如果筛选策略范围设置为消息正文(Message Body),则筛选策略属性将与有效负载进行匹配。
(8)消息安全性
服务器端加密使用AWS KMS提供的加密密钥保护存储在亚马逊SNS主题中的消息内容。还可以在亚马逊SNS与虚拟私有云(VPC)之间建立私有连接,以保护流量的安全性。
2、亚马逊SNS工作原理亚马逊SNS以两种方式发送通知:应用程序间消息(A2A)和应用程序与个人消息(A2P)。
A2A 功能支持在分布式系统、微服务和事件驱动型无服务器应用程序之间进行高吞吐量的多对多消息传递,应用程序包括 Amazon Simple Queue Service (SQS)、Amazon Kinesis Data Firehose、AWS Lambda 以及其他 HTTPS 端点;
A2P 功能允许通过 SMS 文本、推送通知和电子邮件向客户发送消息。
(1)发布/订阅
(2)短信
(3)移动推送
AWS SNS服务充当逻辑接入点,作为通信渠道,让对多个终端节点(如 Amazon AWS Lambda、Amazon SQS、HTTP/S 或电子邮件地址)进行分组。
为广播需要消息的多个服务(如结算系统和执行系统)创建主题非常简单。例如可以为电子商务网站的消息创建一个主题。
在使用 AWS Management Console、AWS SDK for Java 或 AWS SDK for .NET 创建主题的过程中,可以选择主题类型(标准或 FIFO)并为其命名。注意创建后无法更改主题的类型或名称;在创建主题时,所有其他配置选项都是可选的,可以在后续阶段再次进行编辑。
创建AWS SNS服务步骤:
1、登录 Amazon SNS 控制台。
2、执行以下操作之一:
如果 AWS 账户之前未创建过任何主题,请查看 SNS 首页上的说明;
如果之前已经创建过主题,请在导航面板中选择“主题”。
3、在主题页面上,选择“创建主题”。
4、在“创建主题”页面的“详细信息”部分,执行以下操作:
在“类型”中选择主题类型(标准或 FIFO);
输入主题的名称。对于 FIFO 主题,请在名称末尾添加 “.fifo”;
(可选)输入主题的显示名称。
注意: 当订阅电子邮件终端节点时,AWS SNS主题的显示名称和发件邮箱地址(例如 no-reply@sns.amazonaws.com)组合字符数不得超过 320 个 UTF-8 字符。在为 AWS SNS 主题设置显示名称之前,建议使用第三方编码工具来确认发送地址的长度。
5、(可选) 对于 FIFO 主题,可以启用基于内容的消息重复数据删除功能。
6、(可选) 展开加密部分,执行以下操作:
- 选择“启用加密”;
- 为每种 KMS 类型,都会显示描述、账户 KMS ARN 和相关信息;
- 重要提示: 如果不是 KMS 的所有者,或者使用的账户不具备 “kms:ListAliases” 和 “kms:DescribeKey” 权限,则无法在 AWS SNS 控制台上查看 KMS 相关信息;
- 请确保获得 KMS 账户所有者的授权,获取相应权限。
7、(可选) 默认情况下,只有主题拥有者才能发布或订阅主题。要配置额外的访问权限,可以展开访问策略部分。
8、(可选) 配置 AWS SNS 如何重试失败的消息传送尝试,展开传送重试策略(HTTP/S)部分。
9、(可选) 配置 AWS SNS 如何记录消息传输状态到 CloudWatch,展开“传送状态记录”部分。
10、(可选) 如果需要,可以将元数据标签添加到主题中,展开标签部分,输入键和值,然后选择“添加标签”。
11、选择“创建主题”。
创建完成后,将看到“主题已创建”页面,其中显示主题的名称、ARN(Amazon Resource Name)、(可选)显示名称和主题所有者的 AWS 账户 ID。
例如,主题的 ARN 格式如下:
三、使用AWS SDK创建AWS SNS服务arn:aws:sns:us-east-2:123456789012:MyTopic
以下代码示例演示如何使用CreateTopic。
1、.NET2、C++using System;
using System.Threading.Tasks;
using Amazon.SimpleNotificationService;
using Amazon.SimpleNotificationService.Model;/// <summary>
/// This example shows how to use Amazon Simple Notification Service
/// (Amazon SNS) to add a new Amazon SNS topic.
/// </summary>
public class CreateSNSTopic
{
public static async Task Main()
{
string topicName = “ExampleSNSTopic”;IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();
var topicArn = await CreateSNSTopicAsync(client, topicName);
Console.WriteLine($”New topic ARN: {topicArn}”);
}/// <summary>
/// Creates a new SNS topic using the supplied topic name.
/// </summary>
/// <param name=”client”>The initialized SNS client object used to
/// create the new topic.</param>
/// <param name=”topicName”>A string representing the topic name.</param>
/// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
{
var request = new CreateTopicRequest
{
Name = topicName,
};var response = await client.CreateTopicAsync(request);
return response.TopicArn;
}
}
3、AWS CLI//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
\param topicName: An Amazon SNS topic name.
\param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
\param clientConfiguration: AWS client configuration.
\return bool: Function succeeded.
*/
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
Aws::String &topicARNResult,
const Aws::Client::ClientConfiguration &clientConfiguration) {
Aws::SNS::SNSClient snsClient(clientConfiguration);Aws::SNS::Model::CreateTopicRequest request;
request.SetName(topicName);const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);
if (outcome.IsSuccess()) {
topicARNResult = outcome.GetResult().GetTopicArn();
std::cout << “Successfully created an Amazon SNS topic ” << topicName
<< ” with topic ARN ‘” << topicARNResult
<< “‘.” << std::endl;}
else {
std::cerr << “Error creating topic ” << topicName << “:” <<
outcome.GetError().GetMessage() << std::endl;
topicARNResult.clear();
}return outcome.IsSuccess();
}
以下create-topic示例创建了一个名为SNS的主题my-topic。
aws sns create-topic \
–name my-topic
输出:
4、Go V2{
“ResponseMetadata”: {
“RequestId”: “1469e8d7-1642-564e-b85d-a19b4b341f83”
},
“TopicArn”: “arn:aws:sns:us-west-2:123456789012:my-topic”
}
5、Java// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
SnsClient *sns.Client
}// CreateTopic creates an Amazon SNS topic with the specified name. You can optionally
// specify that the topic is created as a FIFO topic and whether it uses content-based
// deduplication instead of ID-based deduplication.
func (actor SnsActions) CreateTopic(topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) {
var topicArn string
topicAttributes := map[string]string{}
if isFifoTopic {
topicAttributes[“FifoTopic”] = “true”
}
if contentBasedDeduplication {
topicAttributes[“ContentBasedDeduplication”] = “true”
}
topic, err := actor.SnsClient.CreateTopic(context.TODO(), &sns.CreateTopicInput{
Name: aws.String(topicName),
Attributes: topicAttributes,
})
if err != nil {
log.Printf(“Couldn’t create topic %v. Here’s why: %v\n”, topicName, err)
} else {
topicArn = *topic.TopicArn
}return topicArn, err
}
6、JavaScriptimport software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.CreateTopicRequest;
import software.amazon.awssdk.services.sns.model.CreateTopicResponse;
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 CreateTopic {
public static void main(String[] args) {
final String usage = “””Usage: <topicName>
Where:
topicName – The name of the topic to create (for example, mytopic).“””;
if (args.length != 1) {
System.out.println(usage);
System.exit(1);
}String topicName = args[0];
System.out.println(“Creating a topic with name: ” + topicName);
SnsClient snsClient = SnsClient.builder()
.region(Region.US_EAST_1)
.build();String arnVal = createSNSTopic(snsClient, topicName);
System.out.println(“The topic ARN is” + arnVal);
snsClient.close();
}public static String createSNSTopic(SnsClient snsClient, String topicName) {
CreateTopicResponse result;
try {
CreateTopicRequest request = CreateTopicRequest.builder()
.name(topicName)
.build();result = snsClient.createTopic(request);
return result.topicArn();} catch (SnsException e) {
System.err.println(e.awsErrorDetails().errorMessage());
System.exit(1);
}
return “”;
}
}
在单独的模块中创建客户端并将其导出。
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 { CreateTopicCommand } from “@aws-sdk/client-sns”;
import { snsClient } from “../libs/snsClient.js”;/**
* @param {string} topicName – The name of the topic to create.
*/
export const createTopic = async (topicName = “TOPIC_NAME”) => {
const response = await snsClient.send(
new CreateTopicCommand({ Name: topicName }),
);
console.log(response);
// {
// ‘$metadata’: {
// httpStatusCode: 200,
// requestId: ‘087b8ad2-4593-50c4-a496-d7e90b82cf3e’,
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// TopicArn: ‘arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME’
// }
return response;
};
相关推荐:
《亚马逊SSL证书怎么领取 AWS SSL证书申请及使用方法》
(本文由美国主机侦探原创,转载请注明出处“美国主机侦探”和原文地址!)

微信扫码加好友进群
主机优惠码及时掌握

QQ群号:938255063
主机优惠发布与交流