LoginSignup
2
0

More than 3 years have passed since last update.

SQS へメッセージの送受信 in Python

Posted at

はじめに

Amazon SQS に Python を使って、メッセージの送信・受信をやってみます。備忘録的なメモ記事です。

SQS Queue 作成

Create queue

image-20210221232528144.png

test queue で、それ以外はデフォルトのまま Create

image-20210221232744295.png

作成完了 URL も表示されている

image-20210221235327143.png

SQS に送信 in Python

SQS へメッセージを送付する、Python のソースコードです。作成した Queue の名前を指定して、3つのメッセージを送っています。

import boto3

name = 'test-queue'
sqs = boto3.resource('sqs')
try:
    queue = sqs.get_queue_by_name(QueueName=name)
except:
    queue = sqs.create_queue(QueueName=name)

msg_num = 3
msg_list = [{'Id' : '{}'.format(i+1), 'MessageBody' : 'msg_{}'.format(i+1)} for i in range(msg_num)]
response = queue.send_messages(Entries=msg_list)
print(response)

実行例

> python3 testsqs.py 
{'Successful': [{'Id': '1', 'MessageId': '526c59a9-61c6-4c22-88ad-4f43df540f6f', 'MD5OfMessageBody': '9980c8a9248139f14f4165e5d53088aa'}, {'Id': '2', 'MessageId': 'cc2b7d8d-06c5-4586-8887-1b18ce8c99a9', 'MD5OfMessageBody': '0fd4e86b2daa009cd9929641dbd7dab6'}, {'Id': '3', 'MessageId': '1064603c-a4bc-4761-bd35-58eca3146dd9', 'MD5OfMessageBody': '8b30166735242c192258d4974f662a5f'}], 'ResponseMetadata': {'RequestId': '9b52941c-bdc9-5486-b679-ccb0c3d02499', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': '9b52941c-bdc9-5486-b679-ccb0c3d02499', 'date': 'Sun, 21 Feb 2021 15:27:21 GMT', 'content-type': 'text/xml', 'content-length': '861'}, 'RetryAttempts': 0}}

Python のプログラムから送付したのちに、マネージドコンソールから確認します

image-20210222000307322.png

Poll for messages

image-20210222000332729.png

3 つメッセージが送信されています

image-20210222000359010.png

Body も確認できます

image-20210222000434512.png

SQS から受信 in Python

SQS からメッセージを受信する、Python ソースコードです。受信したあとに、message.delete() で削除しないと、メッセージはキューに残り続けます。

import boto3

name = 'test-queue'
sqs = boto3.resource('sqs')
queue = sqs.get_queue_by_name(QueueName=name)
while True:
    msg_list = queue.receive_messages(MaxNumberOfMessages=10)
    if msg_list:
        for message in msg_list:
            print(message.body)
            message.delete()
    else:
        break

実行例

> python3 testsqs.py 
msg_3
msg_1
msg_2

参考URL

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0