应用订阅筛选策略 - Amazon Simple Notification Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

应用订阅筛选策略

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

重要

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

Amazon Web Services Management Console

  1. 登录 Amazon SNS 控制台

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

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

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

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

  6. JSON editor(JSON 编辑器)字段中,提供筛选策略的 JSON body(JSON 正文)。

  7. 选择 Save changes(保存更改)。

    Amazon SNS 将您的筛选策略应用到订阅。

Amazon CLI

要使用 Amazon Command Line Interface (Amazon CLI) 应用筛选策略,请使用set-subscription-attributes命令,如以下示例所示。对于 --attribute-name 选项,请指定 FilterPolicy。对于 --attribute-value,请指定您的 JSON policy(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: . . ." } }

Amazon 软件开发工具包

以下代码示例显示了如何使用SetSubscriptionAttributes

重要

如果您使用 SDK for Java 2.x 示例,则类 SNSMessageFilterPolicy 并非开箱即用。有关如何安装该类的说明,请参阅 GitHub 网站上的示例

CLI
Amazon 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
适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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 API 应用筛选策略,需要请求 SetSubscriptionAttributes 操作。将 AttributeName 参数设置为 FilterPolicy,并将 AttributeValue 参数设置为您的筛选策略 JSON。

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

Amazon CloudFormation

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

  1. 登录 Amazon CloudFormation 控制台

  2. 选择创建堆栈

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

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

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

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

      提示

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

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

  6. Review 页面上,选择 Create