Python용 Amazon SNS 확장 클라이언트 라이브러리 - Amazon Simple Notification Service

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Python용 Amazon SNS 확장 클라이언트 라이브러리

사전 조건

다음은 Python용 Amazon SNS 확장 클라이언트 라이브러리 사용을 위한 사전 조건입니다.

  • AWS SDK.

    이 페이지의 예제에서는 AWS Python SDK Boto3를 사용합니다. SDK를 설치하고 설정하려면 Python용AWS SDK 설명서를 참조하세요.

  • 적절한 자격 증명이 AWS 계정 있는 .

    를 생성하려면 AWS 홈 페이지로 AWS 계정이동한 다음 계정 생성을 AWS 선택합니다. 지침을 따릅니다.

    자격 증명에 대한 자세한 내용은 Python용AWS SDK 개발자 안내서에서 자격 증명을 참조하세요.

  • Python 3.x (또는 이후 버전) 및 pip.

  • Python용 Amazon SNS 확장 클라이언트 라이브러리(PyPI에서도 사용 가능).

메시지 스토리지 구성

아래 속성은 Boto3 Amazon SNS 클라이언트, 주제PlatformEndpoint 객체에서 사용할 수 있어 Amazon S3 메시지 스토리지 옵션을 구성할 수 있습니다.

  • large_payload_support — 대용량 메시지를 저장하는 Amazon S3 버킷 이름입니다.

  • message_size_threshold — 대용량 메시지 버킷에 메시지를 저장하기 위한 임계값입니다. 값은 0 이하 또는 262144 이상이면 안 됩니다. 기본값은 262144입니다.

  • always_through_s3True인 경우 모든 메시지가 Amazon S3에 저장됩니다. 기본값은 False입니다.

  • s3 — Amazon S3에 resource 객체를 저장하는 데 사용되는 Boto3 Amazon S3 객체입니다. Amazon S3 리소스(예: 사용자 지정 Amazon S3 구성 또는 자격 증명)를 제어하려면 이 옵션을 사용하세요. 처음 사용할 때 이전에 설정하지 않은 경우 기본값은 boto3.resource("s3")입니다.

예: Amazon S3에 저장된 페이로드로 Amazon SNS에 메시지 게시

다음 코드 예제는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • 샘플 Amazon SNS 주제 및 Amazon SQS 대기열을 생성합니다.

  • 대기열에서 구독하여 주제의 메시지를 수신합니다.

  • 테스트 메시지를 게시합니다.

  • 메시지 페이로드는 Amazon S3에 저장되고 이에 대한 참조가 게시됩니다.

  • 대기열에 게시된 메시지를 Amazon S3에서 검색된 원본 메시지와 함께 인쇄합니다.

대용량 메시지를 게시하려면 Python용 Amazon SNS 확장 클라이언트 라이브러리를 사용하세요. 보내는 메시지는 실제 메시지 내용이 포함된 Amazon S3 객체를 참조합니다.

import boto3 import sns_extended_client from json import loads s3_extended_payload_bucket = "extended-client-bucket-store" TOPIC_NAME = "TOPIC-NAME" QUEUE_NAME = "QUEUE-NAME" # Create an helper to fetch message from S3 def get_msg_from_s3(body): json_msg = loads(body) s3_client = boto3.client("s3") s3_object = s3_client.get_object( Bucket=json_msg[1].get("s3BucketName"), Key=json_msg[1].get("s3Key") ) msg = s3_object.get("Body").read().decode() return msg # Create an helper to fetch and print message SQS queue and S3 def fetch_and_print_from_sqs(sqs, queue_url): """Handy Helper to fetch and print message from SQS queue and S3""" message = sqs.receive_message( QueueUrl=queue_url, MessageAttributeNames=["All"], MaxNumberOfMessages=1 ).get("Messages")[0] message_body = message.get("Body") print("Published Message: {}".format(message_body)) print("Message Stored in S3 Bucket is: {}\n".format(get_msg_from_s3(message_body))) # Initialize the SNS client and create SNS Topic sns_extended_client = boto3.client("sns", region_name="us-east-1") create_topic_response = sns_extended_client.create_topic(Name=TOPIC_NAME) demo_topic_arn = create_topic_response.get("TopicArn") # Create and subscribe an SQS queue to the SNS client sqs = boto3.client("sqs") demo_queue_url = sqs.create_queue(QueueName=QUEUE_NAME).get("QueueUrl") demo_queue_arn = sqs.get_queue_attributes(QueueUrl=demo_queue_url, AttributeNames=["QueueArn"])["Attributes"].get("QueueArn") # Set the RawMessageDelivery subscription attribute to TRUE sns_extended_client.subscribe(TopicArn=demo_topic_arn, Protocol="sqs", Endpoint=demo_queue_arn, Attributes={"RawMessageDelivery":"true"}) sns_extended_client.large_payload_support = s3_extended_payload_bucket # To store all messages content in S3, set always_through_s3 to True # In the example, we set message size threshold as 32 bytes, adjust this threshold as per your usecase # Message will only be uploaded to S3 when its payload size exceeded threshold sns_extended_client.message_size_threshold = 32 sns_extended_client.publish( TopicArn=demo_topic_arn, Message="This message should be published to S3 as it exceeds the message_size_threshold limit", ) # Print message stored in s3 fetch_and_print_from_sqs(sqs, demo_queue_url)

출력

Published Message: [ "software.amazon.payloadoffloading.PayloadS3Pointer", { "s3BucketName": "extended-client-bucket-store", "s3Key": "xxxx-xxxxx-xxxxx-xxxxxx" } ] Message Stored in S3 Bucket is: This message should be published to S3 as it exceeds the message_size_threshold limit