Amazon에서 구독 필터 정책 적용 SNS - Amazon Simple Notification Service

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

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

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

Amazon SNS 콘솔을 사용하여 Amazon SNS 구독에 필터 정책을 적용할 수 있습니다. 또는 정책을 프로그래밍 방식으로 적용하려면 Amazon SNS , AWS Command Line Interface (AWS CLI) 또는 Amazon 를 지원하는 모든 API를 사용할 수 AWS SDK 있습니다SNS. 를 사용할 수도 있습니다 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 본문을 제공합니다.

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

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

AWS CLI

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

$ 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.xSDK용 예제를 사용하는 경우 클래스SNSMessageFilterPolicy를 즉시 사용할 수 없습니다. 이 클래스를 설치하는 방법에 대한 지침은 GitHub 웹 사이트의 예제를 참조하세요.

CLI
AWS CLI

구독 속성을 설정하려면

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

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 예제에서는 FilterPolicy 속성을 SQS 구독으로 설정합니다.

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

Amazon SNS API

Amazon SNS 에 필터 정책을 적용하려면 SetSubscriptionAttributes 작업을 API요청합니다. AttributeName 파라미터를 로 설정하고 AttributeValue 파라미터를 필터 정책 로 FilterPolicy설정합니다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. 에 주제를 구독할 HTTP 엔드포인트를 myHttpEndpoint입력합니다.

      작은 정보

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

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

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