前言
Amazon Simple Notification Service (Amazon SNS) is a web service that coordinates and manages the delivery or sending of messages to subscribing endpoints or clients. In Amazon SNS, there are two types of clients—publishers and subscribers—also referred to as producers and consumers. Publishers communicate asynchronously with subscribers by producing and sending a message to a topic, which is a logical access point and communication channel. Subscribers (i.e., web servers, email addresses, Amazon SQS queues, AWS Lambda functions) consume or receive the message or notification over one of the supported protocols (i.e., Amazon SQS, HTTP/S, email, SMS, Lambda) when they are subscribed to the topic. [1]
正如SNS的介绍所述,SNS是AWS提供的一个消息收发服务,它包括了诸如消息推送、短信、电子邮件等服务。AWS官方文档提供了非常多的内容,但提供的示例代码是以Java或.Net为主,关于Node.js的直接资料较少,所以这里便来介绍如何使用AWS SNS服务发送短信。
Node.js中使用SNS发送短信
在Node.js中使用AWS的服务,需要先安装aws-sdk
依赖。AWS SDK中包括了众多服务的接口,在这里我们需要的是AWS.SNS类。首先,需要实例化AWS.SNS对象,其构造函数的参数为一个对象,通常需要包括accessKeyId
、secretAccessKey
、region
等属性。在AWS IAM中,可生成并下载使用的用户对应的accessKeyId
及secretAccessKey
。需要注意的是,使用的用户需要在IAM中设置SNS对应的权限。
const AWS = require('aws-sdk');
const options = {
accessKeyId: 'String',
secretAccessKey: 'String',
apiVersion: '2010-03-31',
};
const snsService = new AWS.SNS(options);
通过AWS.SNS类的实例,就可以使用其进行SNS服务的相关操作。本文的主题为使用SNS服务发送短信,所以接下来即可通过AWS.SNS实例的publish
方法以短信形式发送消息。
AWS SDK for Node.js中,publish
方法接收一个Object类型的参数,它其中包括Message
、MessageAttributes
、MessageStructure
、PhoneNumber
、Subject
、TargetArn
以及TopicArn
属性。publish
是一个SNS中通用的方法,发送邮件