2016-05-06 111 views
0

我有一個涉及AWS SNSSQS的應用程序,需要在多臺主機上運行。確切的問題描述是:使用多臺主機處理來自AWS SQS的消息

每當發生事件時,包含ID的消息就會發布到SNS主題,該SNS主題具有一個訂閱它的SQS隊列。現在我在隊列中收到消息。現在,我希望多個主機從隊列中讀取消息(沒有兩個主機應該讀取相同的消息),並將消息寫入Amazon S3中的公共文件。應該考慮「如果主機讀取消息失敗」和「在同一主機或不同主機上兩次讀取相同消息」等問題。

任何人都可以提出一些方法或一些參考,我可以通過它來完成這項任務?

+0

你在問什麼,正是SQS所做的。您需要更具體地瞭解您遇到的問題。 –

回答

2

這聽起來像你想要的很大程度上是SQS默認行爲。當某個主機讀取消息時,訪問隊列的其他人不可見,直至消息可見性超時。您可以使api呼叫延長該超時(即某種心跳)。

您也可以配置死信隊列。通過這種方式,在接收到一定數量的消息之後,它將被移動到一個單獨的隊列中,以便以其他方式進行檢查或處理。

這是記錄here

+0

您能否提供一些參考。我正在查看AWS文檔,但沒有找到一個! – rightCoder

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三引號引號。