AWS SNS支持使用过滤策略来选择性地将消息发送到预定的SQS队列中,通过提取消息体中的属性并将它们与标准比较。
以下是将使用AWS SNS和SQS进行消息过滤的示例代码:
首先,我们需要创建格式正确的消息:
import json
message = {"name": "John", "age": 30, "city": "New York"}
sns_message = {"default": json.dumps(message)}
然后,我们需要创建一个SNS主题和两个SQS队列,并在SNS中配置消息过滤策略:
import boto3
sns_client = boto3.client('sns')
sqs_client = boto3.client('sqs')
# 创建SNS主题
topic_arn = sns_client.create_topic(Name='my-topic')['TopicArn']
# 创建两个SQS队列
queue1_url = sqs_client.create_queue(QueueName='my-queue1')['QueueUrl']
queue2_url = sqs_client.create_queue(QueueName='my-queue2')['QueueUrl']
# 配置SNS主题的消息过滤策略
filter_policy = {"city": ["New York"]}
sns_client.set_topic_attributes(TopicArn=topic_arn, AttributeName="FilterPolicy", AttributeValue=json.dumps(filter_policy))
随后,我们需要订阅主题并发布消息:
# 将队列进行订阅
sns_client.subscribe(TopicArn=topic_arn, Protocol='sqs', Endpoint=queue1_url)
sns_client.subscribe(TopicArn=topic_arn, Protocol='sqs', Endpoint=queue2_url)
# 发布消息
sns_client.publish(TopicArn=topic_arn, Message=json.dumps(sns_message))
现在,只有一个队列(在这个例子中是my-queue1)会收到由SNS主题发送的消息,因为仅当消息中的城市属性为“New York”