在 Amazon 中应用订阅筛选政策 SNS - Amazon Simple Notification Service

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

在 Amazon 中应用订阅筛选政策 SNS

Amazon 中的邮件筛选SNS允许您根据筛选策略有选择地向订阅者传送消息。这些策略定义了发送到订阅的消息必须满足的条件。虽然原始消息传送是一个可能影响消息处理的选项,但订阅过滤器并不需要它才能起作用。

您可以使用亚马逊SNS控制台将筛选策略应用于亚马逊SNS订阅。或者,要以编程方式应用政策,您可以使用 Amazon SNS API、 AWS Command Line Interface (AWS CLI) 或任何支持 Amazon AWS SDK SNS 的策略。你也可以使用 AWS CloudFormation。

启用原始消息传送

原始消息交付可确保消息负载按原样交付给订阅者,而无需进行任何额外的编码或转换。当订阅者需要使用原始消息格式进行处理时,这可能很有用。但是,原始消息传递与订阅过滤器的功能没有直接关系。

应用订阅筛选器

要将邮件过滤器应用于订阅,请使用JSON语法定义过滤器策略。该政策规定了消息必须满足的条件才能发送到订阅中。过滤器可以基于消息属性,例如消息属性、消息结构甚至消息内容。

原始消息传送和订阅过滤器之间的关系

虽然启用原始消息传送会影响订阅者传递和处理消息的方式,但这并不是使用订阅过滤器的先决条件。但是,在订阅者需要不做任何修改的原始消息格式的情况下,启用原始消息传送可能与订阅过滤器一起启用。

有效筛选的注意事项

在实现消息过滤时,请考虑您的应用程序和订阅者的特定要求。定义与邮件传送标准精确匹配的过滤策略,以确保高效、有针对性的消息分发。

重要

AWS 诸如IAM和 Amazon 之类的服务SNS使用一种称为最终一致性的分布式计算模型。对订阅筛选器策略的添加或更改最多需要 15 分钟即可完全生效。

AWS Management Console

  1. 登录 Amazon SNS 控制台

  2. 在导航面板中,选择 Subscriptions(订阅)。

  3. 选择订阅,然后选择编辑

  4. Edit(编辑)页面上,展开 Subscription filter policy(订阅筛选策略)部分。

  5. attribute-based filtering(基于属性的筛选)或 payload-based filtering(基于有效负载的筛选)之间进行选择。

  6. JSON编辑器字段中,提供您的筛选策略的JSON正文

  7. 选择保存更改

    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

重要

如果您使用的是 For SDK Java 2.x 示例,则该类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示例为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适用于 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

亚马逊 SNS API

要向 Amazon 应用筛选政策 SNSAPI,请向该SetSubscriptionAttributes操作提出请求。将AttributeName参数设置为FilterPolicy,然后将AttributeValue参数设置为筛选策略JSON。

如果要从基于属性(默认)的消息筛选切换到基于有效负载的消息筛选,您也可以使用 SetSubscriptionAttributes 操作。将 AttributeName 参数设置为 FilterPolicyScope,并将 AttributeValue 参数设置为 MessageBody

AWS CloudFormation

要使用应用筛选策略 AWS CloudFormation,请使用JSON或YAML模板创建 AWS CloudFormation 堆栈。有关更多信息,请参阅《AWS CloudFormation 用户指南》中的AWS::SNS::Subscription资源FilterPolicy性和示例 AWS CloudFormation 模板

  1. 登录 AWS CloudFormation 控制台

  2. 选择创建堆栈

  3. Select Template (选择模板) 页面上,依次选择 Upload a template to Amazon S3 (将模板上传到 Amazon S3)、您的文件和下一步

  4. 指定详细信息页面中,执行以下操作:

    1. 对于堆栈名称,键入 MyFilterPolicyStack

    2. 对于 myHttpEndpoint,键入要订阅您的主题的HTTP终端节点。

      提示

      如果您没有HTTP终端节点,请创建一个。

  5. 选项页面上,选择下一步

  6. Review 页面上,选择 Create