Boto3:有没有一种方法可以正常中断SQS长轮询接收消息请求?

时间:2019-04-13 02:04:56

标签: python amazon-web-services boto amazon-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进程(或者显然等待超时)的停止轮询的方法。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以简单地使用一个标志来做到这一点。假定按钮应中断轮询过程。按下按钮后即可更新标记。然后,当轮询返回一组消息时,您检查该标志,并忽略对消息的处理。不用担心,消息仍然会在队列中。参见:link

  

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))

希望这会有所帮助。