LoginSignup
0
0

More than 3 years have passed since last update.

AWS Lambda(python)によるAmazonSQSの送信と受信サンプル

Last updated at Posted at 2021-02-03

AWS Lambda(python)でAmazonSQSの送信と受信を行ってみます。
エラーハンドリング等は行っていないシンプルなサンプルです。

AmazonSQSのキュー作成

今回は単純な送受信を行うだけなので特別な設定は不要です。
以下の設定で作成します。(記載なしの値はデフォルト)

項目 設定値
名前 SampleQueue
タイプ 標準
アクセスポリシー 指定された AWS アカウント、IAM ユーザー、ロールのみを選択

SQSメッセージ送信用Lambda関数の作成

メッセージ本文と2つの属性を送信します。

SQSSendMessage.py
import boto3

def lambda_handler(event, context):
    sqs = boto3.resource('sqs')
    queue = sqs.get_queue_by_name(QueueName="SampleQueue")
    sqsresponse =queue.send_message(
    MessageBody="2021-02-03 this is message body.",
    MessageAttributes={
        'id': {
            'DataType': 'Number', "StringValue": "123"
        },
        'url': {
            'DataType': 'String','StringValue': "https:hogehoge.aws"
        }
    }

SQSメッセージ受信用Lambda関数の作成

指定したキューのメッセージリスト(最大10)の
全ての属性を取得し、削除します。

SQSReceiveMessage.py
import boto3
import json

def lambda_handler(event, context):
    sqs = boto3.resource('sqs')
    queue = sqs.get_queue_by_name(QueueName="SampleQueue")

    msg_list = queue.receive_messages( MessageAttributeNames=['All'], MaxNumberOfMessages=10)

    if msg_list:
        for msg in msg_list:
            print(msg.body)
            print(msg.message_attributes.get('id').get('StringValue'))
            print(msg.message_attributes.get('url').get('StringValue'))
            msg.delete()

以上

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