How to get all messages in Amazon SQS queue using boto library in Python?

后端 未结 6 2096
陌清茗
陌清茗 2021-02-05 10:49

I\'m working on an application whose workflow is managed by passing messages in SQS, using boto.

My SQS queue is growing gradually, and I have no way to check how many e

6条回答
  •  忘了有多久
    2021-02-05 11:08

    I've been working with AWS SQS queues to provide instant notifications, so I need to be processing all of the messages in real time. The following code will help you to efficiently dequeue (all) messages and handle any errors when removing.

    Note: to remove messages off the queue you need to delete them. I'm using the updated boto3 AWS python SDK, json library, and the following default values:

    import boto3
    import json
    
    region_name = 'us-east-1'
    queue_name = 'example-queue-12345'
    max_queue_messages = 10
    message_bodies = []
    aws_access_key_id = ''
    aws_secret_access_key = ''
    sqs = boto3.resource('sqs', region_name=region_name,
            aws_access_key_id=aws_access_key_id,
            aws_secret_access_key=aws_secret_access_key)
    queue = sqs.get_queue_by_name(QueueName=queue_name)
    while True:
        messages_to_delete = []
        for message in queue.receive_messages(
                MaxNumberOfMessages=max_queue_messages):
            # process message body
            body = json.loads(message.body)
            message_bodies.append(body)
            # add message to delete
            messages_to_delete.append({
                'Id': message.message_id,
                'ReceiptHandle': message.receipt_handle
            })
    
        # if you don't receive any notifications the
        # messages_to_delete list will be empty
        if len(messages_to_delete) == 0:
            break
        # delete messages to remove them from SQS queue
        # handle any errors
        else:
            delete_response = queue.delete_messages(
                    Entries=messages_to_delete)
    

提交回复
热议问题