python - 使用无限循环不断轮询SQS队列

标签 python amazon-sqs

我有一个 SQS 队列,需要不断监视传入消息。一旦消息到达,我会进行一些处理并继续等待下一条消息。我通过设置一个无限循环并在循环结束时暂停 2 秒来实现此目的。这是可行的,但是我忍不住觉得这不是解决不断地对队列进行极点处理的需要的非常有效的方法。

代码示例:

    while (1):
        response = sqs.receive_message(
            QueueUrl=queue_url,
            AttributeNames=[
                'SentTimestamp'
            ],
            MaxNumberOfMessages=1,
            MessageAttributeNames=[
                'All'
            ],
            VisibilityTimeout=1,
            WaitTimeSeconds=1
        )

        try:
            message = response['Messages'][0]
            receipt_handle = message['ReceiptHandle']

            # Delete received message from queue
            sqs.delete_message(
                QueueUrl=queue_url,
                ReceiptHandle=receipt_handle
            )
            msg = message['Body']
            msg_json = eval(msg)
            value1 = msg_json['value1']
            value2 = msg_json['value2']
            process(value1, value2)
        except:
            pass
            #print('Queue empty')
        time.sleep(2)

为了干净地退出脚本(应该不断运行),我捕获了按 Ctrl+C 触发的键盘中断,并执行一些清理例程以正常退出。

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        logout()

是否有更好的方法来实现SQS队列的不断轮询以及2秒的延迟是否必要?我试图不去批评 SQS 服务,但也许这并不重要?

最佳答案

这最终就是 SQS 的工作方式 - 它需要一些东西来轮询它以获取消息。但一些建议:

不要每次都只收到一条消息。做一些类似的事情:

messages = sqs.receive_messages(
        MessageAttributeNames=['All'],
        MaxNumberOfMessages=10,
        WaitTimeSeconds=10
    )
for msg in messages:
    logger.info("Received message: %s: %s", msg.message_id, msg.body)

这会给你带来一些改变。第一件事是您愿意接收最多 10 条消息(这是一次调用中 SQS 的最大数量)。第二个是您最多需要等待 10 秒才能收到消息。来自 SQS 文档:

The duration (in seconds) for which the call waits for a message to arrive in the queue before returning. If a message is available, the call returns sooner than WaitTimeSeconds. If no messages are available and the wait time expires, the call returns successfully with an empty list of messages.

因此,您不需要自己的 sleep 调用 - 如果没有消息,调用将等待直至过期。相反,如果您有大量消息,那么您将尽快获取所有消息,因为代码中不会有自己的 sleep 调用。

关于python - 使用无限循环不断轮询SQS队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63601696/

相关文章:

symfony - 通过 AWS SDK 拒绝访问 SQS

python - django项目中的动态子域和url路径

python - dev_appserver.py 给我一个错误

amazon-web-services - 使用 SQS 和 DLQ 时是否应该禁用 lambda 重试?

java - 将数据从 AWS Lambda 发送到 SQS 队列时连接重置

amazon-web-services - S3 事件的 Cloudformation SQS 策略

python - R: system() 不能使用 .bashrc 中定义的 bash 函数

python - 如何在 Python 中对装饰器进行分组

python - 数据的指数拟合(python)

javascript - 使用 jQuery 从跨域 Ajax 请求接收 XML 响应