AWS SNS (Simple Notification Service) 允许你根据消息属性进行消息过滤,这样订阅者就可以只接收他们感兴趣的消息,而无需接收所有发布到 Topic 的消息。这大大提高了效率,降低了成本。🎉
实现 SNS 消息过滤主要依赖于 Subscription Filter Policies。😎
工作原理:
Filter Policy 语法:
Filter Policy 使用 JSON 格式定义。它指定了订阅者希望接收的消息属性和对应的值。 可以使用多种匹配方式:
{"color": ["red"]} 只接收 color 属性值为 red 的消息。🍎{"order_id": [{"prefix": "ORD-"}]} 接收 order_id 属性值以 ORD- 开头的消息。 🧾{"price": [{"numeric": [">=", 10, "<=", 100]}]} 接收 price 属性值在 10 到 100 之间的消息。 💰{"promotion": [{"exists": true}]} 只接收包含 promotion 属性的消息。 🎁{"discount_code": [{"null": true}]} 只接收 discount_code 属性为空的消息。 💨{"animal": ["dog", "cat", "bird"]} 接收 animal 属性值为 dog, cat 或 bird 的消息。 🐶🐱🐦{"status": [{"anything-but": ["failed", "error"]}]} 接收 status 属性值不是 failed 或 error 的消息。 🚦{"product_id": [{"anything-but": [{"prefix": "TEST-"}]}]} 接收 product_id 属性值不是以 TEST- 开头的消息。🧪示例:
假设我们有一个 SNS Topic 用于发布订单相关的消息。每条消息都包含以下属性:
order_id (String): 订单 IDcustomer_id (String): 客户 IDstatus (String): 订单状态 (e.g., "created", "shipped", "delivered", "cancelled")price (Number): 订单总金额现在,我们有两个订阅者:
我们可以为这两个订阅者设置如下 Filter Policies:
订阅者 A 的 Filter Policy:
{
"status": ["shipped"],
"price": [{"numeric": [">", 50]}]
}
订阅者 B 的 Filter Policy:
{
"customer_id": [{"prefix": "VIP-"}]
}
如何设置 Filter Policy:
可以通过 AWS Management Console、AWS CLI 或 AWS SDK 设置 Filter Policy。
aws sns set-subscription-attributes 命令,并指定 --attribute-name FilterPolicy 和 --attribute-value 参数。 命令行工具非常方便! ⌨️sns.set_subscription_attributes in Python) 来设置 Filter Policy。 🤖最佳实践:
NumberOfMessagesFilteredOut 指标可以帮助你了解有多少消息因为 Filter Policy 而被过滤掉。 数据驱动决策! 📊通过合理使用 SNS Subscription Filter Policies,你可以构建更高效、更灵活的消息通知系统。 希望这些信息对你有所帮助! 😊