AWS has many services that sometimes do just the thing you need. One such great AWS service is what we call ” Simple Queue Service” or SQS in short, Let’s look into it.

We’ll not discuss the basic FAQs like “What is SQS” and “How much does it cost” or “How is it different from SNS”. Because  Amazon SQS FAQs page answers all these questions in detail.

In this post, we are about to see the answers to following two questions:

Where To Use SQS (Simple Queue Service) by AWS?

If you want a queue serving service where you can insert messages, that another machine (or the same machine) can pull & process later, SQS is the thing for you, especially if you’re an AWS fan.

Here are a few ideas/usage that the official  Amazon SQS FAQs Page  by Amazon suggests:

  • Integrate Amazon SQS with other AWS services to make applications more flexible and reliable.
  • Use Amazon SQS to create work queues with each message as a task to be completed by a process. Let one (or many) computers read tasks from the message queue and then process them.
  • Build a microservice architecture and use message queues to connect your microservices.
  • Keep notifications of significant business events in an Amazon SQS message queue. Each event can have a corresponding message in a message queue, and applications that need to be aware of the event can read and process the messages.

and the last question this post answers is

How To Use SQS with PHP

Its very simple to get going with SQS as Amazon already provides the PHP SDK for the purpose. We’ll start by installing the AWS SQS PHP SDK to our project. Let’s divide our jobs into three parts

  • Setting up the SDK
  • Sending data to the queue
  • Retrieving data from the queue

Setting up the SDK

While working with PHP, its always the best to use third-party package managers such as composer.  If you prefer composer and are familiar with it, update your composer.json to require the following.

{
"require": {
  "aws/aws-sdk-php": "dev-master"
 }
}

Once you have included “aws/aws-sdk-php” in your composer.json, its time to run ”composer update” so that the SDK is downloaded and placed into your project.

However, if you don’t prefer using composer. You can instead download the zip file from the SQS PHP SDK Git repo and unzip it into your project directory.

Once you have the SDK in your directory you need to include it into your PHP file, let’s say you are writing your code in the file sqs.php in the root directory.

At the top of your code in sqs.php, you need to add
require '/path/to/aws-autoloader.php';
If you used the ZIP for adding the SDK to your project.

And those who used composer would include the following
require 'vendor/autoload.php'

That’s all about the installation of the SDK into your project, its time to use it.

Sending data to the queue

I have written the following PHP function to send data to an SQS queue

<?php
require 'vendor/autoload.php';

use Aws\Sqs\SqsClient;

//A function to send message to SQS queue
function send_to_sqs(){

//Connect to SQS
$client = SqsClient::factory(array(

'credentials' => array (
'key' => $AWS_KEY, //use your AWS key here
'secret' => $AWS_SECRET //use your AWS secret here
),

'region' => 'us-east-1', //replace it with your region
'version' => 'latest'
));

$client->sendMessage(array(
'QueueUrl' => $queueUrl, //your queue url goes here
'MessageBody' => 'An awesome message!',
));

}
?>

The code above is easy and self-explainatory, yet if you need help, drop a comment and I’ll get back to you.

Moving on to our last step in this post.

Retrieving data from the queue

Well this is really as easy as Amazon claims it to be. Please have a look at my code below that retrieves messages from SQS and deletes them from the queue once processed (to avoid duplicate processing).

<?php
require 'vendor/autoload.php';
use Aws\Sqs\SqsClient;

//A function to send message to SQS queue
function get_from_sqs(){

//Connect to SQS
$client = SqsClient::factory(array(

'credentials' => array (
'key' => $AWS_KEY, //use your AWS key here
'secret' => $AWS_SECRET //use your AWS secret here
),

'region' => 'us-east-1', //replace it with your region
'version' => 'latest'
));

//Getting messages
$result = $client->receiveMessage(array(
'QueueUrl' => $QUEUE_URL, //replace with your Queue URL
));

//Array containing all the messages
$works=$result->getPath('Messages');

if(count($works) > 0){
$k=1;
foreach ($works as $messageBody) {

echo "Processing : #".$k.'...'.PHP_EOL;

// Do something with the message, print for now
print_r($messageBody['Body']);

//work done, remove data from queue
echo "Processed & Deleting : #".$k.'...'.PHP_EOL;

$result = $client->deleteMessageBatch(array(
'QueueUrl' => $QUEUE_URL, //replace this with your Queue URL
'Entries' => array(
array(
'Id' => $messageBody['MessageId'],
'ReceiptHandle' => $messageBody['ReceiptHandle'],
)
)
));

$k++;
}

}else{
echo "No data in queue, Complete!".PHP_EOL;
}

}
?>

Hope you find it useful, questions and suggestions are welcomed.


Also published on Medium.

Categories: Tech Blog