쿠키 기본 설정 선택

당사는 사이트와 서비스를 제공하는 데 필요한 필수 쿠키 및 유사한 도구를 사용합니다. 고객이 사이트를 어떻게 사용하는지 파악하고 개선할 수 있도록 성능 쿠키를 사용해 익명의 통계를 수집합니다. 필수 쿠키는 비활성화할 수 없지만 '사용자 지정' 또는 ‘거부’를 클릭하여 성능 쿠키를 거부할 수 있습니다.

사용자가 동의하는 경우 AWS와 승인된 제3자도 쿠키를 사용하여 유용한 사이트 기능을 제공하고, 사용자의 기본 설정을 기억하고, 관련 광고를 비롯한 관련 콘텐츠를 표시합니다. 필수가 아닌 모든 쿠키를 수락하거나 거부하려면 ‘수락’ 또는 ‘거부’를 클릭하세요. 더 자세한 내용을 선택하려면 ‘사용자 정의’를 클릭하세요.

Amazon SNS에서 구독 필터 정책 적용

포커스 모드
Amazon SNS에서 구독 필터 정책 적용 - Amazon Simple Notification Service

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

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

Amazon SNS에서 메시지 필터링을 사용하면 필터 정책에 따라 구독자에게 선택적으로 메시지를 전달할 수 있습니다. 이러한 정책에서는 메시지가 구독에 전달되려면 충족되어야 하는 조건을 정의합니다. 원시 메시지 전송은 메시지 처리에 영향을 미칠 수 있는 옵션이지만 구독 필터가 작동하는 데 필수는 아닙니다.

Amazon SNS 콘솔을 사용하여 필터 정책을 Amazon SNS 구독에 적용할 수 있습니다. 또는 프로그래밍 방식으로 정책을 적용하려면 Amazon SNS API, AWS Command Line Interface (AWS CLI) 또는 Amazon SNS를 지원하는 AWS SDK를 사용할 수 있습니다. 를 사용할 수도 있습니다 AWS CloudFormation.

원시 메시지 전송 사용

원시 메시지 전송을 사용하면 추가 인코딩 또는 변환 없이 메시지 페이로드를 구독자에게 있는 그대로 전달할 수 있습니다. 이는 구독자가 처리하는 데 원본 메시지 형식을 필요로 하는 경우에 유용할 수 있습니다. 하지만 원시 메시지 전송은 구독 필터의 기능과는 직접적인 관련이 없습니다.

구독 필터 적용

메시지 필터를 구독에 적용하려면 JSON 구문을 사용하여 필터 정책을 정의합니다. 이 정책에서는 메시지가 구독에 전달되려면 충족되어야 하는 조건을 지정합니다. 필터는 메시지 속성, 메시지 구조, 메시지 콘텐츠와 같은 메시지 속성을 기반으로 작동할 수 있습니다.

원시 메시지 전송과 구독 필터 간의 관계

원시 메시지 전송을 사용하면 구독자가 메시지를 전송하고 처리하는 방식에 영향을 미칠 수 있지만 구독 필터를 사용하기 위한 사전 조건은 아닙니다. 하지만 구독자가 수정 없이 원본 메시지 형식을 요구하는 시나리오에서는 구독 필터와 함께 원시 메시지 전송을 사용하는 것이 도움이 될 수 있습니다.

효과적인 필터링을 위한 고려 사항

메시지 필터링을 구현할 경우 애플리케이션 및 구독자의 특정 요구 사항을 고려하세요. 메시지 전송 기준과 정확하게 일치하는 필터 정책을 정의하여 효율적이고 대상에 맞게 메시지를 배포합니다.

중요

AWS IAM 및 Amazon SNS와 같은 서비스는 최종 일관성이라는 분산 컴퓨팅 모델을 사용합니다. 구독 필터 정책의 추가 또는 변경 사항이 완전히 적용되려면 최대 15분이 소요됩니다.

AWS Management Console

  1. Amazon SNS 콘솔에 로그인합니다.

  2. 탐색 창에서 구독을 선택합니다.

  3. 구독을 선택한 후 편집을 선택합니다.

  4. 편집(Edit) 페이지에서 구독 필터 정책(Subscription filter policy) 섹션을 확장합니다.

  5. 속성 기반 필터링 또는 페이로드 기반 필터링 중에서 선택합니다.

  6. JSON 편집기(JSON editor) 필드에서 필터 정책의 JSON 본문(JSON body)을 제공합니다.

  7. Save changes(변경 사항 저장)를 선택합니다.

    Amazon SNS에서 구독에 필터 정책을 적용합니다.

AWS CLI

AWS Command Line Interface (AWS CLI)를 사용하여 필터 정책을 적용하려면 다음 예제와 같이 set-subscription-attributes 명령을 사용합니다. --attribute-name 옵션의 경우 FilterPolicy를 지정합니다. --attribute-value의 경우 JSON 정책을 지정합니다.

$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicy --attribute-value '{"store":["example_corp"],"event":["order_placed"]}'

정책에 유효한 JSON을 제공하려면 속성 이름과 값을 큰 따옴표로 묶습니다. 또한 전체 정책 인수를 따옴표로 묶어야 합니다. 따옴표 이스케이프를 방지하려면, 위의 예제와 같이 작은따옴표를 사용하여 정책을 묶고 큰따옴표를 사용하여 JSON 이름과 값을 묶을 수 있습니다.

속성 기반(기본값)에서 페이로드 기반 메시지 필터링으로 전환하려면 set-subscription-attributes 명령도 사용할 수 있습니다. --attribute-name 옵션의 경우 FilterPolicyScope를 지정합니다. --attribute-value에서 MessageBody를 지정합니다.

$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicyScope --attribute-value MessageBody

필터 정책이 적용되었는지 확인하려면 get-subscription-attributes 명령을 사용합니다. 터미널 출력의 속성에는 다음 예제와 같이 FilterPolicy 키에 대한 필터 정책이 표시되어야 합니다:

$ aws sns get-subscription-attributes --subscription-arn arn:aws:sns: ... { "Attributes": { "Endpoint": "endpoint . . .", "Protocol": "https", "RawMessageDelivery": "false", "EffectiveDeliveryPolicy": "delivery policy . . .", "ConfirmationWasAuthenticated": "true", "FilterPolicy": "{\"store\": [\"example_corp\"], \"event\": [\"order_placed\"]}", "FilterPolicyScope": "MessageAttributes", "Owner": "111122223333", "SubscriptionArn": "arn:aws:sns: . . .", "TopicArn": "arn:aws:sns: . . ." } }

AWS SDKs

다음 코드 예제는 SetSubscriptionAttributes의 사용 방법을 보여 줍니다.

중요

Java 2.x 예제용 SDK를 사용하는 경우 클래스 SNSMessageFilterPolicy는 즉시 사용할 수 없습니다. 이 클래스를 설치하는 방법에 대한 지침은 GitHub 웹 사이트의 예제를 참조하세요.

CLI
AWS CLI

구독 속성을 설정하려면

다음 set-subscription-attributes예제에서는 SQS 구독에 RawMessageDelivery속성을 설정합니다.

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name RawMessageDelivery \ --attribute-value true

이 명령은 출력을 생성하지 않습니다.

다음 set-subscription-attributes예제에서는 SQS 구독에 FilterPolicy속성을 설정합니다.

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }"

이 명령은 출력을 생성하지 않습니다.

다음 set-subscription-attributes예제에서는 SQS 구독에서 FilterPolicy속성을 제거합니다.

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{}"

이 명령은 출력을 생성하지 않습니다.

Java
SDK for Java 2.x
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.ArrayList; /** * 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 UseMessageFilterPolicy { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of a subscription. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); usePolicy(snsClient, subscriptionArn); snsClient.close(); } public static void usePolicy(SnsClient snsClient, String subscriptionArn) { try { SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy(); // Add a filter policy attribute with a single value fp.addAttribute("store", "example_corp"); fp.addAttribute("event", "order_placed"); // Add a prefix attribute fp.addAttributePrefix("customer_interests", "bas"); // Add an anything-but attribute fp.addAttributeAnythingBut("customer_interests", "baseball"); // Add a filter policy attribute with a list of values ArrayList<String> attributeValues = new ArrayList<>(); attributeValues.add("rugby"); attributeValues.add("soccer"); attributeValues.add("hockey"); fp.addAttribute("customer_interests", attributeValues); // Add a numeric attribute fp.addAttribute("price_usd", "=", 0); // Add a numeric attribute with a range fp.addAttributeRange("price_usd", ">", 0, "<=", 100); // Apply the filter policy attributes to an Amazon SNS subscription fp.apply(snsClient, subscriptionArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
Python
SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def add_subscription_filter(subscription, attributes): """ Adds a filter policy to a subscription. A filter policy is a key and a list of values that are allowed. When a message is published, it must have an attribute that passes the filter or it will not be sent to the subscription. :param subscription: The subscription the filter policy is attached to. :param attributes: A dictionary of key-value pairs that define the filter. """ try: att_policy = {key: [value] for key, value in attributes.items()} subscription.set_attributes( AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy) ) logger.info("Added filter to subscription %s.", subscription.arn) except ClientError: logger.exception( "Couldn't add filter to subscription %s.", subscription.arn ) raise
AWS CLI

구독 속성을 설정하려면

다음 set-subscription-attributes예제에서는 SQS 구독에 RawMessageDelivery속성을 설정합니다.

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name RawMessageDelivery \ --attribute-value true

이 명령은 출력을 생성하지 않습니다.

다음 set-subscription-attributes예제에서는 SQS 구독에 FilterPolicy속성을 설정합니다.

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }"

이 명령은 출력을 생성하지 않습니다.

다음 set-subscription-attributes예제에서는 SQS 구독에서 FilterPolicy속성을 제거합니다.

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{}"

이 명령은 출력을 생성하지 않습니다.

Amazon SNS API

Amazon SNS API를 사용하여 필터 정책을 적용하려면 SetSubscriptionAttributes 작업에 대한 요청을 수행합니다. AttributeName 파라미터를 FilterPolicy로 설정하고 AttributeValue 파라미터를 필터 정책 JSON으로 설정합니다.

속성 기반(기본값)에서 페이로드 기반 메시지 필터링으로 전환하려는 경우에도 SetSubscriptionAttributes 작업을 사용할 수 있습니다. AttributeName 매개 변수를 FilterPolicyScope로 설정하고 AttributeValue 매개 변수를 MessageBody로 설정합니다.

AWS CloudFormation

를 사용하여 필터 정책을 적용하려면 JSON 또는 YAML 템플릿을 AWS CloudFormation사용하여 스택을 AWS CloudFormation 생성합니다. 자세한 내용은 AWS CloudFormation 사용 설명서AWS::SNS::Subscription 리소스 FilterPolicy 속성예제 AWS CloudFormation 템플릿을 참조하세요.

  1. AWS CloudFormation 콘솔에 로그인합니다.

  2. 스택 생성을 선택합니다.

  3. 템플릿 선택 페이지에서 Amazon S3에 템플릿 업로드를 선택하고 파일을 선택한 후 다음을 선택합니다.

  4. 세부 정보 지정 페이지에서 다음 작업을 수행합니다.

    1. 스택 이름MyFilterPolicyStack을 입력합니다.

    2. myHttpEndpoint에 주제를 구독할 HTTP 엔드포인트를 입력합니다.

      작은 정보

      HTTP 엔드포인트가 없는 경우 하나를 생성합니다.

  5. 옵션 페이지에서 다음을 선택합니다.

  6. 검토 페이지에서 생성을 선택합니다.

이 페이지에서

프라이버시사이트 이용 약관쿠키 기본 설정
© 2025, Amazon Web Services, Inc. 또는 계열사. All rights reserved.