AWS SQS NodeJS Example
We can quickly get started with SQS by using the AWS SDKs, samples, and how-tos. From Java and Ruby to .NET and Python, you can use SQS in your applications in a few lines of code.
In our case, we'll use NodeJS, and the code is available from Github (https://github.com/Einsteinish/aws-sqs-node-js-example).
Follow the instructions below on an EC2 Ubuntu instance to setup the AWS SDK using NodeJS:
sudo su apt-get update apt-get upgrade -y apt-get dist-upgrade -y apt-get autoremove -y apt-get install nodejs npm git -y ln -s /usr/bin/nodejs /usr/bin/node git clone https://github.com/Einsteinish/aws-sqs-node-js-example.git cd aws-sqs-node-js-example
Now we want to install express and aws-sdk:
npm install
Then, we may want to put our secret key info to config.json:
cp config-sample.json config.json
Let's start our node app:
# node app.js AWS SQS example app listening at http://:::80
We can see it's running on port 80.
Let's look at the code in app.js:
... // Creating a queue. app.get('/create', function (req, res) { var params = { QueueName: "MyFirstQueue" }; sqs.createQueue(params, function(err, data) { if(err) { res.send(err); } else { res.send(data); } }); }); ...
On the browser, type in "create" with public ip address. Then, we'll get a response back:
Now we have "QueueUrl", and we can see we have "MyFirstQueue" in SQS console:
To use Amazon SQS Message Attributes, please check Using Amazon SQS Message Attributes
Let's copy the "QueueUrl" so that we can use it in app.js:
// Require objects. var express = require('express'); var app = express(); var aws = require('aws-sdk'); var queueUrl = "https://sqs.us-west-1.amazonaws.com/526262051452/MyFirstQueue"; var receipt = ""; ...
After putting in the "QueueUrl", let's restart our app:
# node app.js AWS SQS example app listening at http://:::80
Now, we want to send a message to the queue. Let's look the code that's responsible for sending a message:
... // Sending a message. // NOTE: Here we need to populate the queue url you want to send to. // That variable is indicated at the top of app.js. app.get('/send', function (req, res) { var params = { MessageBody: 'Hello world!', QueueUrl: queueUrl, DelaySeconds: 0 }; sqs.sendMessage(params, function(err, data) { if(err) { res.send(err); } else { res.send(data); } }); }); ...
To send a message, on the browser, we can type "send" after the endpoint:
As we can see from the screen shot, we got a valid response and a "MessageID", and our message is the message queue. We can check it from SQS:
After refreshing the page, we can notice we have 1 message is available from the "Message Available" column.
Now that we know we have the message in the queue, let's try to receive the message from the queue. Again, the code snippet of app.js for the "receive":
... // Receive a message. // NOTE: This is a great long polling example. You would want to perform // this action on some sort of job server so that you can process these // records. In this example I'm just showing you how to make the call. // It will then put the message "in flight" and I won't be able to // reach that message again until that visibility timeout is done. app.get('/receive', function (req, res) { var params = { QueueUrl: queueUrl, VisibilityTimeout: 600 // 10 min wait time for anyone else to process. }; sqs.receiveMessage(params, function(err, data) { if(err) { res.send(err); } else { res.send(data); } }); }); ...
We can check if we received the message by using "receive" API:
We can see we got the "Hello world!" message.
On SQS console, we can see there is "1" in the "Message in Flight" column:
A message is considered to be in flight after it's received from a queue by a consumer, but not yet deleted from the queue.
For standard queues, there can be a maximum of 120,000 inflight messages per queue. If we reach this limit, Amazon SQS returns the OverLimit error message. To avoid reaching the limit, we should delete messages from the queue after they're processed. We can also increase the number of queues we use to process our messages.
Let's copy the ReceiptHandle:
Then, put it into app.js like this:
// Require objects. var express = require('express'); var app = express(); var aws = require('aws-sdk'); var queueUrl = "https://sqs.us-west-1.amazonaws.com/526262051452/MyFirstQueue"; var receipt = "AQEBOQmPpQ3BI7lry0Dyx3kyyVoPrCklOEc7j5OrQK3btzR9IJJNz5wEb3el85bU36yXSVzWhedaY9y8IcVd3QOq8SUpnm4pQPTJx9g62pulH7OaG1kJboIrvHWMG9Sh4+Vk2+lcS9hus+WiO5cqdVY1Ed642Tnnxzg2GUEGKi62mBkBf7g3o1SuXei6FNF+Ld9IjoAhX6hYTnI/2l0IX//XI2p1ukce9PHriTf5DuIVNSCwY1jx6dr7YefCD8gXimYmSR9BPI6jmA6Vfs3+074z9q1U+zWQbcJnxxXbTnzLQQ4mPHHpqi2s2emGl+1WoddUAV27I3LhoyjNlmb4URI9GEirOifr+jfZ+wbSymjk/BzZKDvO9greJpmiF62EvpuPrPnvpAUrdGt2FXmxFVToog=="; ...
Here is the delete portion of the code in app.js:
... // Deleting a message. app.get('/delete', function (req, res) { var params = { QueueUrl: queueUrl, ReceiptHandle: receipt }; sqs.deleteMessage(params, function(err, data) { if(err) { res.send(err); } else { res.send(data); } }); }); ...
Make sure we restart the app, then we can try to delete the message:
Refresh SQS screen, then we can see there is no more messages:
Just for a demonstration purpose, we can send multiple message. Let's send the same message 5 times by refreshing it 5 times:
On SQS screen, we can check if we have the 5 messages in the queue:
Note: This tutorial is largely based on Simple Queue Service (SQS) Tutorial NodeJS + AWS SDK
AWS (Amazon Web Services)
- AWS : EKS (Elastic Container Service for Kubernetes)
- AWS : Creating a snapshot (cloning an image)
- AWS : Attaching Amazon EBS volume to an instance
- AWS : Adding swap space to an attached volume via mkswap and swapon
- AWS : Creating an EC2 instance and attaching Amazon EBS volume to the instance using Python boto module with User data
- AWS : Creating an instance to a new region by copying an AMI
- AWS : S3 (Simple Storage Service) 1
- AWS : S3 (Simple Storage Service) 2 - Creating and Deleting a Bucket
- AWS : S3 (Simple Storage Service) 3 - Bucket Versioning
- AWS : S3 (Simple Storage Service) 4 - Uploading a large file
- AWS : S3 (Simple Storage Service) 5 - Uploading folders/files recursively
- AWS : S3 (Simple Storage Service) 6 - Bucket Policy for File/Folder View/Download
- AWS : S3 (Simple Storage Service) 7 - How to Copy or Move Objects from one region to another
- AWS : S3 (Simple Storage Service) 8 - Archiving S3 Data to Glacier
- AWS : Creating a CloudFront distribution with an Amazon S3 origin
- AWS : Creating VPC with CloudFormation
- AWS : WAF (Web Application Firewall) with preconfigured CloudFormation template and Web ACL for CloudFront distribution
- AWS : CloudWatch & Logs with Lambda Function / S3
- AWS : Lambda Serverless Computing with EC2, CloudWatch Alarm, SNS
- AWS : Lambda and SNS - cross account
- AWS : CLI (Command Line Interface)
- AWS : CLI (ECS with ALB & autoscaling)
- AWS : ECS with cloudformation and json task definition
- AWS Application Load Balancer (ALB) and ECS with Flask app
- AWS : Load Balancing with HAProxy (High Availability Proxy)
- AWS : VirtualBox on EC2
- AWS : NTP setup on EC2
- AWS: jq with AWS
- AWS & OpenSSL : Creating / Installing a Server SSL Certificate
- AWS : OpenVPN Access Server 2 Install
- AWS : VPC (Virtual Private Cloud) 1 - netmask, subnets, default gateway, and CIDR
- AWS : VPC (Virtual Private Cloud) 2 - VPC Wizard
- AWS : VPC (Virtual Private Cloud) 3 - VPC Wizard with NAT
- DevOps / Sys Admin Q & A (VI) - AWS VPC setup (public/private subnets with NAT)
- AWS - OpenVPN Protocols : PPTP, L2TP/IPsec, and OpenVPN
- AWS : Autoscaling group (ASG)
- AWS : Setting up Autoscaling Alarms and Notifications via CLI and Cloudformation
- AWS : Adding a SSH User Account on Linux Instance
- AWS : Windows Servers - Remote Desktop Connections using RDP
- AWS : Scheduled stopping and starting an instance - python & cron
- AWS : Detecting stopped instance and sending an alert email using Mandrill smtp
- AWS : Elastic Beanstalk with NodeJS
- AWS : Elastic Beanstalk Inplace/Rolling Blue/Green Deploy
- AWS : Identity and Access Management (IAM) Roles for Amazon EC2
- AWS : Identity and Access Management (IAM) Policies, sts AssumeRole, and delegate access across AWS accounts
- AWS : Identity and Access Management (IAM) sts assume role via aws cli2
- AWS : Creating IAM Roles and associating them with EC2 Instances in CloudFormation
- AWS Identity and Access Management (IAM) Roles, SSO(Single Sign On), SAML(Security Assertion Markup Language), IdP(identity provider), STS(Security Token Service), and ADFS(Active Directory Federation Services)
- AWS : Amazon Route 53
- AWS : Amazon Route 53 - DNS (Domain Name Server) setup
- AWS : Amazon Route 53 - subdomain setup and virtual host on Nginx
- AWS Amazon Route 53 : Private Hosted Zone
- AWS : SNS (Simple Notification Service) example with ELB and CloudWatch
- AWS : Lambda with AWS CloudTrail
- AWS : SQS (Simple Queue Service) with NodeJS and AWS SDK
- AWS : Redshift data warehouse
- AWS : CloudFormation
- AWS : CloudFormation Bootstrap UserData/Metadata
- AWS : CloudFormation - Creating an ASG with rolling update
- AWS : Cloudformation Cross-stack reference
- AWS : OpsWorks
- AWS : Network Load Balancer (NLB) with Autoscaling group (ASG)
- AWS CodeDeploy : Deploy an Application from GitHub
- AWS EC2 Container Service (ECS)
- AWS EC2 Container Service (ECS) II
- AWS Hello World Lambda Function
- AWS Lambda Function Q & A
- AWS Node.js Lambda Function & API Gateway
- AWS API Gateway endpoint invoking Lambda function
- AWS API Gateway invoking Lambda function with Terraform
- AWS API Gateway invoking Lambda function with Terraform - Lambda Container
- Amazon Kinesis Streams
- AWS: Kinesis Data Firehose with Lambda and ElasticSearch
- Amazon DynamoDB
- Amazon DynamoDB with Lambda and CloudWatch
- Loading DynamoDB stream to AWS Elasticsearch service with Lambda
- Amazon ML (Machine Learning)
- Simple Systems Manager (SSM)
- AWS : RDS Connecting to a DB Instance Running the SQL Server Database Engine
- AWS : RDS Importing and Exporting SQL Server Data
- AWS : RDS PostgreSQL & pgAdmin III
- AWS : RDS PostgreSQL 2 - Creating/Deleting a Table
- AWS : MySQL Replication : Master-slave
- AWS : MySQL backup & restore
- AWS RDS : Cross-Region Read Replicas for MySQL and Snapshots for PostgreSQL
- AWS : Restoring Postgres on EC2 instance from S3 backup
- AWS : Q & A
- AWS : Security
- AWS : Security groups vs. network ACLs
- AWS : Scaling-Up
- AWS : Networking
- AWS : Single Sign-on (SSO) with Okta
- AWS : JIT (Just-in-Time) with Okta
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization