[AWS] Operate SQS from SDK (send / receive) [Python] [Node.js]

I often use Lambda x SQS

I often use SQS, so I will write a sample of sending and receiving. This article has a great meaning as a memorandum of my own.

Premise

Receive message from SQS

Get messages from SQS using Python

sample


# -*- coding: utf-8 -*-

from __future__ import print_function
import ConfigParser
import boto3
import json

#Read config file
ini = ConfigParser.SafeConfigParser()
ini.read("./config.ini")

# sqs
sqs = boto3.client('sqs')
sqsUrl = ini.get("sqs", "url")

#Maximum number of messages to retrieve
limit = 100

#Processing body
print('Loading function...')
def lambda_handler(event, context):
    print('========== FUNCTION START ==========')
    
    for cnt in range(0, limit):
        queMessage = get_sqs_message(sqsUrl)

        if queMessage is not None:
            if "Messages" in queMessage:
                receiptHandle = queMessage['Messages'][0]['ReceiptHandle']
                message = queMessage['Messages'][0]['Body']
                print('receiptHandle:' + str(receiptHandle))
                print('messageBody:' + str(message))
            else:
                print('no message')
                break
        else:
            ercnt += 1
            print("ERROR COUNT:" + str(ercnt))

    print('========== FUNCTION END ============')


#SQS message acquisition process
def get_sqs_message(sqs_url):
    url = sqs_url

    try:
        response = sqs.receive_message(
            QueueUrl=url,
        )

    except Exception as e:
        print('=====Error=====')
        print('get_sqs_message')
        print('ERROR:' + str(e))
        print('===============')
        return None

    return response

Receiving from SQS is possible if you know the URL.

Get a message from SQS using node.js

sample


//Module loading
var aws = require('aws-sdk');
var sqs = new aws.SQS({region: 'ap-northeast-1'});

//Maximum number of messages to retrieve
var limit = 100;

//URL of sqs
var ini = require('./config.json');
var url = ini.sqs.url.test

//Main processing
exports.handler = function (event, context) {
	var cnt = 0;
	var params = {
			QueueUrl: url
	};

	for (var i = 0; i < limit; i++) {
	cnt++;
			sqs.receiveMessage(params, function (err, data) {
					if (err) {
							console.log(err, err.stack);
					} else {
							if (data.Messages) {
									var messageBody = data.Messages[0].Body;
									var receiptHandle = data.Messages[0].ReceiptHandle;
									console.log(messageBody);
									console.log(receiptHandle);
							} 
					}
					if (cnt === limit) context.succeed();
			});
	}
};
    

config.json


{
  "sqs": {
    "url": {
      "test": "https://sqs.ap-northeast-1.amazonaws.com/************/hogehoge-test"
    }
}

I wrote the node side in json.


Send a message to SQS

Now send a message to SQS

Send a message to SQS using Python

sample


# -*- coding: utf-8 -*-

from __future__ import print_function
import ConfigParser
import boto3


#Read config file
ini = ConfigParser.SafeConfigParser()
ini.read("./config.ini")

# sqs
sqs = boto3.client('sqs')
sqsUrl = ini.get("sqs", "url")


#Processing body
print('Loading function...')
def lambda_handler(event, context):
    print('========== FUNCTION START ==========')

    message = 'hogeeeeeeeeee'
    send_sqs_message(sqsUrl, message)

    print('========== FUNCTION END ============')


#SQS message transmission processing
def send_sqs_message(sqs_url, send_message):
    url = sqs_url
    obj = send_message

    try:
        response = sqs.send_message(
            MessageBody = obj,
            QueueUrl = url,
            DelaySeconds = 0
        )

    except Exception as e:
        print('=====Error=====')
        print('send_sqs_message')
        print('ERROR:' + str(e))
        print('===============')
        return None

    return response

Send a message to SQS using node.js

sample



//Module loading
var aws = require('aws-sdk');
var sqs = new aws.SQS({region: 'ap-northeast-1'});

//URL of sqs
var ini = require('./config.json');
var url = ini.sqs.url.test;

//Main processing
exports.handler = function (event, context) {
    var message = 'hogeeeeeeee';
    var params = {
        MessageBody: message,
        QueueUrl: url,
        DelaySeconds: 0
    };

    sqs.sendMessage(params, function (err, data) {
        if (err) {
          console.log(err, err.stack)
        } else {
            console.log(data);
            context.succeed();
        }
    });

};


__ As you can see, I'm not good at node. __

By the way, why two languages? Because I use both

Recommended Posts

[AWS] Operate SQS from SDK (send / receive) [Python] [Node.js]
Call Polly from the AWS SDK for Python
Operate Filemaker from Python
Operate neutron from Python!
Operate LXC from Python
Operate an I2C-connected display from Python
Operate DynamoDB from Python like SQL.
boto3 (AWS SDK for Python) Note
Receive textual data from mysql with python
Send a message from Python to Slack
Operate Sakura's cloud object storage from Python
I made a library to operate AWS CloudFormation stack from CUI (Python Fabric)
I made a Docker image that can call FBX SDK Python from Node.js
Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack
Send a message from Slack to a Python server
Send data from Raspberry Pi using AWS IOT
Operate the schedule app using python from iphone