将 Amazon SNS 与 Amazon CLI 结合使用 - Amazon Command Line Interface
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文档仅适用于 Amazon CLI 版本 1。有关 Amazon CLI 版本 2 的相关文档,请参阅版本 2 用户指南

将 Amazon SNS 与 Amazon CLI 结合使用

您可以使用 Amazon Command Line Interface (Amazon CLI)访问 Amazon Simple Notification Service (Amazon SNS) 的功能。要列出适用于 Amazon SNS 的 Amazon CLI 命令,请使用以下命令。

aws sns help

在运行任何命令之前,请设置默认证书。有关更多信息,请参阅 配置Amazon CLI

本主题显示执行 Amazon SNS 常见任务的 Amazon CLI 命令。

创建主题

要创建主题,请使用 sns create-topic 命令并指定要分配给该主题的名称。

$ aws sns create-topic --name my-topic { "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic" }

记下响应的 TopicArn,您随后将用它来发布消息。

订阅主题

要订阅主题,请使用 sns subscribe 命令。

以下示例为 email 指定 notification-endpoint 协议和电子邮件地址。

$ aws sns subscribe --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --protocol email --notification-endpoint saanvi@example.com { "SubscriptionArn": "pending confirmation" }

Amazon 通过向您在 subscribe 命令中指定的地址发送电子邮件,立即发送确认电子邮件。电子邮件具有以下文本。

You have chosen to subscribe to the topic: arn:aws:sns:us-west-2:123456789012:my-topic To confirm this subscription, click or visit the following link (If this was in error no action is necessary): Confirm subscription

收件人单击确认订阅链接后,收件人的浏览器显示通知消息,信息类似于以下内容。

Subscription confirmed! You have subscribed saanvi@example.com to the topic:my-topic. Your subscription's id is: arn:aws:sns:us-west-2:123456789012:my-topic:1328f057-de93-4c15-512e-8bb22EXAMPLE If it was not your intention to subscribe, click here to unsubscribe.

向主题发布

要将消息发送给某一主题的所有订阅者,请使用 sns publish 命令。

以下示例发送消息“Hello World!” 特定主体的所有订阅者。

$ aws sns publish --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic --message "Hello World!" { "MessageId": "4e41661d-5eec-5ddf-8dab-2c867EXAMPLE" }

在本示例中,Amazon将包含文本“Hello World!”的电子邮件发送 到 saanvi@example.com

取消订阅主题

要取消订阅某个主题并停止接收向该主题发布的消息,请使用 sns unsubscribe 命令并指定您要取消订阅的主题的 ARN。

$ aws sns unsubscribe --subscription-arn arn:aws:sns:us-west-2:123456789012:my-topic:1328f057-de93-4c15-512e-8bb22EXAMPLE

要验证您已成功取消订阅,请使用 sns list-subscriptions 命令以确认该 ARN 不再显示在列表中。

$ aws sns list-subscriptions

删除主题

要删除主题,请运行 sns delete-topic 命令。

$ aws sns delete-topic --topic-arn arn:aws:sns:us-west-2:123456789012:my-topic

要验证 Amazon 是否已成功删除主题,请使用 sns list-topics 命令以确认该主题不再显示在列表中。

$ aws sns list-topics