Amazon SNS 消息交付狀態 - Amazon Simple Notification Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

Amazon SNS 消息交付狀態

Amazon SNS 提供支援,以記錄傳送至具有下列 Amazon SNS 端點主題的通知訊息的交付狀態:

  • HTTP

  • Amazon 數據 Firehose

  • AWS Lambda

  • 平台應用程式端點

  • Amazon Simple Queue Service

設定郵件傳遞狀態屬性之後,會針對傳送給主題訂閱者的郵件,將 CloudWatch 記錄項目傳送至記錄檔。記錄訊息傳遞狀態有助於提供深入的營運見解,例如下列項目:

  • 知道訊息是否已傳遞至 Amazon SNS 端點。

  • 識別從 Amazon SNS 端點發送到 Amazon 的響應SNS。

  • 決定訊息停留時間 (發佈時間戳記之間的時間與移交給 Amazon SNS 端點之前的時間)。

若要設定郵件傳遞狀態的主題屬性,您可以使用 AWS Management Console, AWS 軟體開發套件 (SDKs) API、查詢或 AWS CloudFormation。

使用 AWS Management Console設定交付狀態記錄日誌

  1. 登錄到 Amazon 控SNS制台

  2. 在導覽面板上,選擇 Topics (主題)

  3. Topics (主題) 頁面上,選擇主題,然後選擇 Delete (刪除)

  4. 在編MyTopic頁面上,展開 [傳送狀態記錄] 區段。

  5. 選擇您希望記錄交付狀態日誌的通訊協定,例如 AWS Lambda

  6. 輸入成功取樣率 (您要接收 CloudWatch 記錄檔的成功訊息百分比)。

  7. 在「IAM角色」區段中,執行下列其中一項作業:

    • 若要從您的帳戶中選擇現有的服務角色,請選擇 [使用現有的服務IAM角色],然後指定成功和失敗傳送的角色。

    • 若要在您的帳戶中建立新的服務角色,請選擇 [建立新服務角色],選擇 [建立新角色] 以定義IAM主控台中成功和失敗傳送的IAM角色。

      若要授予 Amazon SNS 寫入權限以代表您使用 CloudWatch 日誌,請選擇 [允許]。

  8. 選擇儲存變更

    您現在可以檢視和剖析包含郵件傳遞狀態的 CloudWatch 記錄檔。如需使用的詳細資訊 CloudWatch,請參閱CloudWatch文件

使用設定傳送狀態記錄 AWS SDKs

提 AWS SDKs供多種APIs語言,可將訊息傳遞狀態屬性與 Amazon 搭配使用SNS。

主題屬性

您可以使用下列訊息傳遞狀態的主題屬性名稱值:

HTTP

  • HTTPSuccessFeedbackRoleArn— 指出訂閱HTTP端點之 Amazon SNS 主題的成功訊息傳遞狀態。

  • HTTPSuccessFeedbackSampleRate— 指出訂閱HTTP端點之 Amazon SNS 主題要取樣的成功訊息百分比。

  • HTTPFailureFeedbackRoleArn— 指示訂閱HTTP端點之 Amazon SNS 主題的失敗訊息傳遞狀態。

Amazon 數據 Firehose

  • FirehoseSuccessFeedbackRoleArn— 指出訂閱 Amazon Kinesis 資料火管端點之亞馬遜SNS主題的成功訊息傳遞狀態。

  • FirehoseSuccessFeedbackSampleRate— 針對訂閱 Amazon Amazon Kinesis Data Firehose 端點之 Amazon SNS 主題,指出要取樣的成功訊息百分比。

  • FirehoseFailureFeedbackRoleArn— 指出訂閱 Amazon Kinesis 資料火管端點之亞馬遜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 日誌。<ENDPOINT>SuccessFeedbackSampleRate 屬性用於指定成功傳送訊息的取樣率百分比 (0-100)。設定<ENDPOINT>FailureFeedbackRoleArn屬性之後,所有失敗的郵件傳遞都會產生 CloudWatch 記錄檔。

AWS SDK配置主題屬性的範例

下列程式碼範例會示範如何使用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

此命令不會產生輸出。

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參考SetTopicAttributes中的。

JavaScript
SDK對於 JavaScript (3)
注意

還有更多關於 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
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關詳細資訊,請參閱SetTopicAttributesAWS SDK的以取得 Kotlin API 的參考資料

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()); }
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對於 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細資訊,請參閱SetTopicAttributesAWS SDK的以供SAPABAPAPI參考

使用 AWS CloudFormation設定交付狀態記錄日誌

若要DeliveryStatusLogging使用進行設定 AWS CloudFormation,請使用JSON或YAML範本建立 AWS CloudFormation 堆疊。若要取得更多資訊,請參閱《 AWS CloudFormation 使用指南》中的AWS::SNS::Topic資源DeliveryStatusLogging屬性。以下是範 AWS CloudFormation 本範例,YAML以JSON及建立新主題或使用 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