使用多个主机

时间:2016-05-06 10:36:46

标签: amazon-web-services amazon-sqs event-driven-design

我有一个涉及AWS SNSSQS的应用程序,需要在多个主机上运行。确切的问题描述是:

每当有事件发生时,包含ID的消息就会发布到SNS主题,该主题订阅了SQS队列。现在我在队列中收到消息。现在,我希望多个主机从队列中读取消息(没有两个主机应该读取相同的消息)并将消息写入Amazon S3中的公共文件。应该考虑诸如“如果主机阅读消息失败”和“不在同一主机或不同主机中两次读取相同消息”之类的问题。

有人可以提出一些方法或一些参考资料,通过这些方法我可以通过它来完成这项任务吗?

2 个答案:

答案 0 :(得分:2)

听起来你想要的主要是SQS在默认情况下的表现。当其中一个主机读取消息时,对于访问队列的其他人来说,它将变为不可见,直到消息可见性超时。您可以进行api调用以延长该超时(即一种心跳)。

您还可以配置死信队列。有了这个,在收到一定数量的消息后,它会被移动到一个单独的队列,用于检查或以其他方式处理。

记录在案here

答案 1 :(得分:0)

解决方案分散在各地。 您可以阅读SQS Dead Letter queue setup并参考我的示例。您无需编码即可使用AWS SQS控制台执行完全相同的操作。

import boto3
sqs = boto3.client("sqs")
# I want to "lock" my queue for 5 minutes to allow my process have time to 
# complete the task and delete the message afterwards.
response = sqs.create_queue(
    QueueName="foo",
    Attributes= {
        "VisibilityTimeout" : "300"
    }
)
# create a queue to store the "dead letter message"
dlq_response = sqs.create_queue(
    QueueName="dlq-foo",
    Attributes= {
        "VisibilityTimeout" : "300"
    }
)
queue_url = response["QueueUrl"]

# Attach RedrivePolicy to drive message to dead letter queue 
# I want to make sure the message only read 1 time. Assume the program crash
# if it is not deleted.
# deadLetterTargetArn : You must specify the queue exact region name, 
# exact Account name(replace 1234567890) and your dead letter queue name dlq-foo
sqs.set_queue_attributes(
    QueueUrl = queue_url,
    Attributes = {
        "RedrivePolicy" : """{
                "maxReceiveCount" : "1" ,
                "deadLetterTargetArn" : "arn:aws:sqs:<region-name>:1234567890:dlq-foo"
            }"""
        }
    )

注意:RedrivePolicy只访问文字字符串,而不是字典。但是,正如doucumentation指出的那样,你需要在其中加上“dictionary like”值并将其格式化为字符串。您可以使用str(dict())将dict转换为字符串,我使用python三引号引用以获得清晰度。