Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
Amazon SNS 消息传送状态
Amaz SNS on 支持使用以下亚马逊SNS终端节点记录发送到主题的通知消息的发送状态:
配置消息传送状态属性后,发送给主题订阅者的消息的 CloudWatch 日志条目将发送到日志。记录消息传输状态有助于提供更好的业务洞察力,例如以下方面:
-
知道消息是否已传送到 Amazon SNS 终端节点。
-
识别从亚马逊SNS终端节点发送到亚马逊的响应SNS。
-
确定消息停留时间(从发布时间戳到传送到 Amazon SNS 终端节点之前的时间)。
要为消息传送状态配置主题属性,您可以使用 Amazon 软件开发套件 (SDKs) API、查询或 Amazon CloudFormation。 Amazon Web Services Management Console
使用 Amazon Web Services Management Console配置传输状态日志记录
登录 Amazon SNS 控制台。
-
在导航面板上,选择 Topics(主题)。
-
在主题页面上,选择主题,然后选择编辑。
-
在 E dit 中 MyTopic
页面上,展开 “配送状态记录” 部分。
-
选择要记录其传输状态日志的协议,例如 Amazon Lambda。
-
输入成功采样率(您希望接收 CloudWatch 日志的成功消息的百分比)。
-
在 “IAM角色” 部分中,执行以下任一操作:
-
选择 Save changes(保存更改)。
现在,您可以查看和解析包含消息传送状态的 CloudWatch 日志。有关使用的更多信息 CloudWatch,请参阅CloudWatch文档。
使用配置传送状态日志 Amazon SDKs
Amazon SDKs提供了多种语言版本,用于APIs在 Amazon 中使用消息传送状态属性SNS。
主题属性
您可以对消息传输状态使用下列主题属性名称值:
HTTP
-
HTTPSuccessFeedbackRoleArn
— 表示已订阅HTTP终端节点的 Amazon SNS 主题的成功消息传送状态。
-
HTTPSuccessFeedbackSampleRate
— 表示已订阅HTTP终端节点的 Amazon SNS 主题成功采样消息的百分比。
-
HTTPFailureFeedbackRoleArn
— 表示已订阅HTTP终端节点的 Amazon SNS 主题的消息传送失败状态。
Amazon Data Firehose
-
FirehoseSuccessFeedbackRoleArn
— 表示已订阅亚马逊 Kinesis Data Firehose 终端节点的亚马逊SNS主题的成功消息传输状态。
-
FirehoseSuccessFeedbackSampleRate
— 表示已订阅亚马逊 Kinesis Data Firehose 终端节点的亚马逊SNS主题成功采样消息的百分比。
-
FirehoseFailureFeedbackRoleArn
— 表示订阅了亚马逊 Kinesis Data Firehose 终端节点的亚马逊SNS主题的消息传输失败状态。
Amazon Lambda
-
LambdaSuccessFeedbackRoleArn
— 表示已订阅 Lambda 终端节点的亚马逊SNS主题的成功消息传输状态。
-
LambdaSuccessFeedbackSampleRate
— 表示已订阅 Lambda 终端节点的 Amazon SNS 主题成功采样消息的百分比。
-
LambdaFailureFeedbackRoleArn
— 表示订阅 Lambda 终端SNS节点的亚马逊主题的消息传输失败状态。
平台应用程序终端节点
-
ApplicationSuccessFeedbackRoleArn
— 表示已订阅 Amazon 应用程序终端节点的 Amazon SNS 主题的成功消息传送状态。
-
ApplicationSuccessFeedbackSampleRate
— 表示已订阅 Amazon 应用程序终端节点的 Amazon SNS 主题成功采样消息的百分比。
-
ApplicationFailureFeedbackRoleArn
— 表示已订阅 Amazon 应用程序终端节点的 Amazon SNS 主题的消息传送失败状态。
Amazon SQS
-
SQSSuccessFeedbackRoleArn
— 表示已订阅亚马逊SQS终端节点的亚马逊SNS主题的成功消息传送状态。
-
SQSSuccessFeedbackSampleRate
— 表示已订阅亚马逊SQS终端节点的亚马逊SNS主题成功采样消息的百分比。
-
SQSFailureFeedbackRoleArn
— 表示已订阅亚马逊SQS终端节点的亚马逊SNS主题的消息传送失败状态。
<ENDPOINT>SuccessFeedbackRoleArn
和<ENDPOINT>FailureFeedbackRoleArn
属性用于向 Amazon 授予代表您使用 CloudWatch 日志的SNS写入权限。<ENDPOINT>SuccessFeedbackSampleRate
属性用于指定成功传输消息的采样率百分比 (0-100)。配置该<ENDPOINT>FailureFeedbackRoleArn
属性后,所有失败的消息传送都会生成 CloudWatch 日志。
Amazon SDK配置主题属性的示例
以下代码示例演示如何使用 SetTopicAttributes
。
- 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
-
- SDK适用于 Java 2.x
-
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);
}
}
}
- JavaScript
-
- SDK对于 JavaScript (v3)
-
在单独的模块中创建客户端并将其导出。
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
-
- SDK对于 Kotlin 来说
-
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.")
}
}
- PHP
-
- SDK for PHP
-
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());
}
- Ruby
-
- SDK对于 Ruby
-
# 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对于 SAP ABAP
-
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.
要DeliveryStatusLogging
使用进行配置 Amazon CloudFormation,请使用JSON或YAML模板创建 Amazon CloudFormation 堆栈。有关更多信息,请参阅《 Amazon CloudFormation 用户指南》中的AWS::SNS::Topic
资源DeliveryStatusLogging
属性。以下是JSON和中的 Amazon CloudFormation 模板示例YAML,用于创建新主题或使用亚马逊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