Boto3:有没有办法优雅地中断 SQS 长轮询接收消息请求



我已经成功创建了一个使用长轮询从 SQS 队列中提取消息的方法,如下所示:

def dequeue_message(self, callback):
    result = self.queue.receive_messages(MaxNumberOfMessages=1)
    if len(result) != 0:
        body = result[0].body
        try:
            callback(body)
            result.delete()
        except Exception as e:
            print("message not dequeued because an error occurred"
                  "when running callback: " + str(e))

但是我找不到一种方法在不杀死正在运行的 Python 进程的情况下停止轮询(或者,显然,等待超时(。我能做什么?

您可以简单地使用标志执行此操作。假设按钮应中断轮询过程。按下按钮后,立即更新标志。然后,当轮询返回一组消息时,检查标志,并忽略处理消息。不用担心,消息仍将在队列中。请参阅:链接

Amazon SQS 在收到消息后不会自动删除消息 对于您,如果您没有成功收到消息(对于 例如,使用者可能会失败或失去连接(。要删除 消息,您必须发送单独的请求,以确认您 不再需要该消息,因为您已成功收到并且 处理了它。

示例代码

# This is the flag to check for interruptions
is_interrupted = False
# This function will set the flag if an interruption is occurred
def interrupt_polling():
    is_interrupted = True

def dequeue_message(self, callback):
    result = self.queue.receive_messages(MaxNumberOfMessages=1)
    # this is the check that will bypass the Polling process
    # Handle this logic as required
    if is_interrupted:
        # assuming that this needs to be reset to False
        is_interrupted = False
        return
    if len(result) != 0:
        body = result[0].body
        try:
            callback(body)
            result.delete()
        except Exception as e:
            print("message not dequeued because an error occurred"
                  "when running callback: " + str(e))

希望这有帮助。

最新更新