iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📩

How to Poll SQS Queues and Receive Messages with Boto3

に公開
2021/04/22

As the title suggests, this article explains how to poll an Amazon SQS queue using Boto3 (AWS SDK for Python) and display the received messages.

Preparation

Granting Permissions

Whether you are running this on EC2 or Lambda, make sure to assign the IAM policy required to read SQS messages.
(For Lambda, the AWSLambdaSQSQueueExecutionRole is sufficient.)

Managing permissions via IAM roles is easier than using access keys, so associate an IAM role with the necessary policies to your EC2 instance or Lambda function.
In this example, since I am running this temporarily on EC2, I will use the EC2PowerUserAccessRole.

Preparing the Queue and Messages

Create an SQS queue in advance.

Since Boto3 will access the queue and receive messages using the value in the URL column, make a note of this value.

Next, to populate the SQS queue with test messages, select the [Send and receive messages] button and add some sample messages to the queue.

Enter text in the message input screen and finally select [Send message].

The message is now in the queue.
Returning to the queue list screen, you can see that one message is now in the queue.
Let's retrieve this message using Boto3.

Implementation with Boto3 (Receiving Messages)

Create a file named receive_message_from_sqs.py on your EC2 instance and write the following code.
Make sure to install the necessary modules like boto3 using pip.

import boto3

queue_url = "https://sqs.ap-northeast-1.amazonaws.com/XXXXXXXXXXX/test-sqs"
region = "ap-northeast-1"

sqs_client = boto3.client("sqs", region_name=region)
response = sqs_client.receive_message(QueueUrl=queue_url, MaxNumberOfMessages=1, VisibilityTimeout=60)

for res in response['Messages']:
  if 'Body' in res:
    print(res['Body'])

The "XXXXXXXXXXXX" part should correspond to your AWS account ID.

When the message is successfully retrieved, the output will look like this:

$ python3 receive_message_from_sqs.py
Test message placed in the queue

The test message you set has been successfully retrieved.

Incidentally, if you check the queue list screen again at this point, you will notice that the count of 1 under "Messages available" has moved to "Messages in flight."

Since VisibilityTimeout=60 is set in the Boto3 code, only the client that called it (in this case, the EC2 instance) can exclusively handle the message during this period.
This is an important mechanism to prevent other clients from operating on or reading the message while a time-consuming process is being executed, and it is thanks to this mechanism that loosely coupled systems can be built.

Discussion