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

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

Amazon SNS 消息传输状态

对于使用下列 Amazon SNS 终端节点的主题,Amazon SNS 支持记录发送到这些主题的通知消息的传输状态:

  • HTTP

  • 亚马逊 Data Firehose

  • Amazon Lambda

  • 平台应用程序终端节点

  • Amazon Simple Queue Service

配置消息传送状态属性后,发送给主题订阅者的消息的 CloudWatch 日志条目将发送到日志。记录消息传输状态有助于提供更好的业务洞察力,例如以下方面:

  • 了解消息是否已传输到 Amazon SNS 终端节点。

  • 识别从 Amazon SNS 终端节点发送到 Amazon SNS 的响应。

  • 确定消息停留时间(发布时间戳与将消息转交给 Amazon SNS 终端节点之间的时间差)。

要配置用于消息传输状态的主题属性,您可以使用 Amazon Web Services Management Console、Amazon 软件开发工具包 (SDK)、查询 API 或 Amazon CloudFormation。

使用 Amazon Web Services Management Console配置传输状态日志记录

  1. 登录 Amazon SNS 控制台

  2. 在导航面板上,选择 Topics(主题)。

  3. 主题页面上,选择主题,然后选择编辑

  4. “编辑” MyTopic页面上,展开 “配送状态记录” 部分。

  5. 选择要记录其传输状态日志的协议,例如 Amazon Lambda

  6. 输入成功采样率(您要接收 CloudWatch 日志的成功消息的百分比)。

  7. IAM roles(IAM 角色)子部分中,执行下列操作之一:

    • 要从您的账户中选择一个现有服务角色,请选择 Use existing service role (使用现有服务角色),然后指定成功和失败传输的 IAM 角色。

    • 要在您的账户中创建新的服务角色,请选择 Create new service role (创建新的服务角色),选择 Create new roles (创建新角色),以便在 IAM 控制台中为成功和失败的传输定义 IAM 角色。

      要向 Amazon SNS 授予代表您使用 CloudWatch 日志的写入权限,请选择 “允许”。

  8. 选择 ‬保存更改

    现在,您可以查看和解析包含消息传送状态的 CloudWatch 日志。有关使用的更多信息 CloudWatch,请参阅CloudWatch文档

使用 Amazon SDK 配置传输状态日志记录

Amazon 开发工具包提供了多种语言的 API,以便将消息传输状态属性用于 Amazon SNS。

主题属性

您可以对消息传输状态使用下列主题属性名称值:

HTTP

  • HTTPSuccessFeedbackRoleArn – 表示订阅到 HTTP 端点的 Amazon SNS 主题的成功消息传输状态。

  • HTTPSuccessFeedbackSampleRate – 表示订阅到 HTTP 端点的 Amazon SNS 主题的成功消息采样百分比。

  • HTTPFailureFeedbackRoleArn – 表示订阅到 HTTP 端点的 Amazon SNS 主题的失败消息传输状态。

亚马逊 Data Firehose

  • FirehoseSuccessFeedbackRoleArn – 表示订阅到 Amazon Kinesis Data Firehose 端点的 Amazon SNS 主题的成功消息传输状态。

  • FirehoseSuccessFeedbackSampleRate – 表示订阅到 Amazon Kinesis Data Firehose 端点的 Amazon SNS 主题的成功消息采样百分比。

  • FirehoseFailureFeedbackRoleArn – 表示订阅到 Amazon Kinesis Data Firehose 端点的 Amazon SNS 主题的失败消息传输状态。

Amazon Lambda

  • LambdaSuccessFeedbackRoleArn – 表示订阅到 Lambda 端点的 Amazon SNS 主题的成功消息传输状态。

  • LambdaSuccessFeedbackSampleRate – 表示订阅到 Lambda 端点的 Amazon SNS 主题的成功消息采样百分比。

  • LambdaFailureFeedbackRoleArn – 表示订阅到 Lambda 端点的 Amazon SNS 主题的失败消息传输状态。

平台应用程序终端节点

  • ApplicationSuccessFeedbackRoleArn – 表示订阅到 Amazon 应用程序端点的 Amazon SNS 主题的成功消息传输状态。

  • ApplicationSuccessFeedbackSampleRate – 表示订阅到 Amazon 应用程序端点的 Amazon SNS 主题的成功消息采样百分比。

  • ApplicationFailureFeedbackRoleArn – 表示订阅到 Amazon 应用程序端点的 Amazon SNS 主题的失败消息传输状态。

    注意

    除了能够为发送到 Amazon SNS 应用程序终端节点的通知消息的消息传输状态配置主题属性,您还可以为发送到推送通知服务的推送通知消息的传输状态配置应用程序属性。有关更多信息,请参阅使用用于消息传输状态的 Amazon SNS 应用程序属性

Amazon SQS

  • SQSSuccessFeedbackRoleArn – 表示订阅到 Amazon SQS 端点的 Amazon SNS 主题的成功消息传输状态。

  • SQSSuccessFeedbackSampleRate – 表示订阅到 Amazon SQS 端点的 Amazon SNS 主题的成功消息采样百分比。

  • SQSFailureFeedbackRoleArn – 表示订阅到 Amazon SQS 端点的 Amazon SNS 主题的失败消息传输状态。

注意

<ENDPOINT>SuccessFeedbackRoleArn<ENDPOINT>FailureFeedbackRoleArn属性用于向 Amazon SNS 授予代表您使用 CloudWatch 日志的写入权限。<ENDPOINT>SuccessFeedbackSampleRate 属性用于指定成功传输消息的采样率百分比 (0-100)。配置该<ENDPOINT>FailureFeedbackRoleArn属性后,所有失败的消息传送都会生成 CloudWatch 日志。

用于配置主题属性的 Amazon 开发工具包示例

以下代码示例演示了如何设置 Amazon SNS 主题属性。

CLI
Amazon CLI

为主题设置属性

以下 set-topic-attributes 示例为指定主题设置 DisplayName 属性。

aws sns set-topic-attributes \ --topic-arn arn:aws:sns:us-west-2:123456789012:MyTopic \ --attribute-name DisplayName \ --attribute-value MyTopicDisplayName

此命令不生成任何输出。

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.SetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse; 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 SetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <attribute> <topicArn> <value> Where: attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy . topicArn - The ARN of the topic.\s value - The value for the attribute. """; if (args.length < 3) { System.out.println(usage); System.exit(1); } String attribute = args[0]; String topicArn = args[1]; String value = args[2]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setTopAttr(snsClient, attribute, topicArn, value); snsClient.close(); } public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) { try { SetTopicAttributesRequest request = SetTopicAttributesRequest.builder() .attributeName(attribute) .attributeValue(value) .topicArn(topicArn) .build(); SetTopicAttributesResponse result = snsClient.setTopicAttributes(request); System.out.println( "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn() + " updated " + request.attributeName() + " to " + request.attributeValue()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.xAPI 参考SetTopicAttributes中的。

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 { SetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const setTopicAttributes = async ( topicArn = "TOPIC_ARN", attributeName = "DisplayName", attributeValue = "Test Topic", ) => { const response = await snsClient.send( new SetTopicAttributesCommand({ AttributeName: attributeName, AttributeValue: attributeValue, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };
Kotlin
适用于 Kotlin 的 SDK
注意

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

suspend fun setTopAttr(attribute: String?, topicArnVal: String?, value: String?) { val request = SetTopicAttributesRequest { attributeName = attribute attributeValue = value topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> snsClient.setTopicAttributes(request) println("Topic ${request.topicArn} was updated.") } }
  • 有关 API 的详细信息,请参阅适用SetTopicAttributes于 K otlin 的 Amazon SDK API 参考

PHP
适用于 PHP 的 SDK
注意

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

require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sns\SnsClient; /** * Configure the message delivery status attributes for 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' ]); $attribute = 'Policy | DisplayName | DeliveryPolicy'; $value = 'First Topic'; $topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic'; try { $result = $SnSclient->setTopicAttributes([ 'AttributeName' => $attribute, 'AttributeValue' => $value, 'TopicArn' => $topic, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHPAPI 参考SetTopicAttributes中的。

Ruby
适用于 Ruby 的 SDK
注意

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

# Service class to enable an SNS resource with a specified policy class SnsResourceEnabler # Initializes the SnsResourceEnabler with an SNS resource client # # @param sns_resource [Aws::SNS::Resource] The SNS resource client def initialize(sns_resource) @sns_resource = sns_resource @logger = Logger.new($stdout) end # Sets a policy on a specified SNS topic # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource to include in the policy # @param policy_name [String] The name of the policy attribute to set def enable_resource(topic_arn, resource_arn, policy_name) policy = generate_policy(topic_arn, resource_arn) topic = @sns_resource.topic(topic_arn) topic.set_attributes({ attribute_name: policy_name, attribute_value: policy }) @logger.info("Policy #{policy_name} set successfully for topic #{topic_arn}.") rescue Aws::SNS::Errors::ServiceError => e @logger.error("Failed to set policy: #{e.message}") end private # Generates a policy string with dynamic resource ARNs # # @param topic_arn [String] The ARN of the SNS topic # @param resource_arn [String] The ARN of the resource # @return [String] The policy as a JSON string def generate_policy(topic_arn, resource_arn) { Version: "2008-10-17", Id: "__default_policy_ID", Statement: [{ Sid: "__default_statement_ID", Effect: "Allow", Principal: { "AWS": "*" }, Action: ["SNS:Publish"], Resource: topic_arn, Condition: { ArnEquals: { "AWS:SourceArn": resource_arn } } }] }.to_json end end # Example usage: if $PROGRAM_NAME == __FILE__ topic_arn = "MY_TOPIC_ARN" # Should be replaced with a real topic ARN resource_arn = "MY_RESOURCE_ARN" # Should be replaced with a real resource ARN policy_name = "POLICY_NAME" # Typically, this is "Policy" sns_resource = Aws::SNS::Resource.new enabler = SnsResourceEnabler.new(sns_resource) enabler.enable_resource(topic_arn, resource_arn, policy_name) end
SAP ABAP
SDK for SAP ABAP
注意

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

TRY. lo_sns->settopicattributes( iv_topicarn = iv_topic_arn iv_attributename = iv_attribute_name iv_attributevalue = iv_attribute_value ). MESSAGE 'Set/updated SNS topic attributes.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY.
  • 有关 API 的详细信息,请参阅适用SetTopicAttributes于 S AP 的 Amazon SDK ABAP API 参考

使用 Amazon CloudFormation 配置传输状态日志记录

要使用 Amazon CloudFormation 配置 DeliveryStatusLogging,请使用 JSON 或 YAML 模板创建 Amazon CloudFormation 堆栈。有关更多信息,请参阅《Amazon CloudFormation 用户指南》中的“AWS::SNS::Topic 资源的 DeliveryStatusLogging 属性”。以下是 JSON 和 YAML Amazon CloudFormation 模板示例,这些模板使用 Amazon SQS 协议的所有 DeliveryStatusLogging 属性创建新主题或更新现有主题。

JSON
"Resources": { "MySNSTopic" : { "Type" : "AWS::SNS::Topic", "Properties" : { "TopicName" : "TestTopic", "DisplayName" : "TEST", "SignatureVersion" : "2", "DeliveryStatusLogging" : [{ "Protocol": "sqs", "SuccessFeedbackSampleRate": "45", "SuccessFeedbackRoleArn": "arn:aws:iam::123456789012:role/SNSSuccessFeedback_test1", "FailureFeedbackRoleArn": "arn:aws:iam::123456789012:role/SNSFailureFeedback_test2" }] } } }
YAML
Resources: MySNSTopic: Type: AWS::SNS::Topic Properties: TopicName:TestTopic DisplayName:TEST SignatureVersion:2 DeliveryStatusLogging: - Protocol: sqs SuccessFeedbackSampleRate: 45 SuccessFeedbackRoleArn: arn:aws:iam::123456789012:role/SNSSuccessFeedback_test1 FailureFeedbackRoleArn: arn:aws:iam::123456789012:role/SNSFailureFeedback_test2