针对FIFO队列,消息组ID可确保先入先出的顺序。AWS控制台如何接收具有相同消息组ID的多个FIFO队列消息呢?AWS SNS提供一种解决方法,即设置SNS订阅FIFO队列。通过将SNS作为中介,消息可以在通过SNS传输时获取唯一的消息组ID。 AWS SNS还提供了一些有用的选项,例如将错误发送到SNS,而不是直接到达AWS Lambda。
以下是设置SNS订阅FIFO队列的Python代码示例:
import boto3
sqs = boto3.client('sqs')
sns = boto3.client('sns')
queue_url = 'https://sqs.us-east-2.amazonaws.com/123456789012/my-queue.fifo'
topic_arn = 'arn:aws:sns:us-east-2:123456789012:my-topic.fifo'
# Create SQS queue
response = sqs.create_queue(
QueueName='my-queue.fifo',
Attributes={
'FifoQueue': 'true',
'ContentBasedDeduplication': 'true'
}
)
queue_url = response['QueueUrl']
# Create SNS Topic
response = sns.create_topic(
Name='my-topic.fifo',
Attributes={
'FifoTopic': 'true'
}
)
topic_arn = response['TopicArn']
# Subscribe SQS queue to SNS Topic
response = sns.subscribe(
TopicArn=topic_arn,
Protocol='sqs',
Endpoint=queue_url,
Attributes={
'FilterPolicy': '{"department": ["finance", "engineering"]}',
'RawMessageDelivery': 'true'
}
)
创建SNS订阅后,如果队列具有相同的消息组ID,AWS SNS将自动将它们合并为一条消息发送到SNS主题中,从而避免了AWS控制台重复接收消息的问题。