Amazon SNS 消息传输状态 - Amazon Simple Notification Service

Amazon SNS 消息传输状态

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

  • HTTP

  • Amazon Data Firehose

  • AWS Lambda

  • 平台应用程序终端节点

  • Amazon Simple Queue Service

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

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

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

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

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

使用 AWS Management Console配置传输状态日志记录

  1. 登录 Amazon SNS 控制台

  2. 在导航面板上,选择主题

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

  4. 编辑我的主题页上,展开 Delivery status logging (传输状态日志记录) 部分。

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

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

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

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

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

      要给予 Amazon SNS 写入权限以代表您使用 CloudWatch Logs,请选择 Allow(允许)。

  8. 选择保存更改

    现在您就可以查看和分析包含消息传输状态的 CloudWatch Logs 了。有关使用 CloudWatch 的更多信息,请参阅 CloudWatch 文档

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

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

主题属性

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

HTTP

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

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

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

Amazon Data Firehose

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

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

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

AWS Lambda

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

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

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

平台应用程序终端节点

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

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

  • ApplicationFailureFeedbackRoleArn – 表示订阅到 AWS 应用程序端点的 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 Logs。<ENDPOINT>SuccessFeedbackSampleRate 属性用于指定成功传输消息的采样率百分比 (0-100)。配置 <ENDPOINT>FailureFeedbackRoleArn 属性以后,所有失败的消息传输都会生成 CloudWatch Logs。

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

以下代码示例演示如何使用 SetTopicAttributes

CLI
AWS 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

此命令不生成任何输出。

  • 有关 API 详细信息,请参阅《AWS CLI Command Reference》中的 SetTopicAttributes

Java
适用于 Java 的 SDK 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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 详细信息,请参阅《AWS SDK for Java 2.x API Reference》中的 SetTopicAttributes

JavaScript
SDK for JavaScript (v3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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

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,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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 详细信息,请参阅《AWS SDK for Kotlin API 参考》中的 SetTopicAttributes

PHP
适用于 PHP 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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 详细信息,请参阅《AWS SDK for PHP API Reference》中的 SetTopicAttributes

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

# 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,了解更多信息。查找完整示例,学习如何在 AWS 代码示例存储库中进行设置和运行。

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 详细信息,请参阅适用于 SAP ABAP 的 AWS SDK 的 API 参考中的 SetTopicAttributes

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

要使用 AWS CloudFormation 配置 DeliveryStatusLogging,请使用 JSON 或 YAML 模板创建 AWS CloudFormation 堆栈。有关更多信息,请参阅《AWS CloudFormation 用户指南》中的“AWS::SNS::Topic 资源的 DeliveryStatusLogging 属性”。以下是 JSON 和 YAML AWS 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