Wednesday, November 5, 2014

Perl script to fetch multiple messages from an Amazon SQS queue

A way out to retrieve multiple messages in a batch from an AWS queue.
#!/usr/bin/perl

use Amazon::SQS::Simple; # module required for accesing Amazon SQS

# Amazon AWS credentials
my $access_key = 'xxxxxxxxxxxxxxxx'; # Your AWS Access Key ID
my $secret_key = 'xxxxxxxxxxxxxxxx'; # Your AWS Secret Key

my $sqs = new Amazon::SQS::Simple($access_key, $secret_key); # Create a SQS object providing the AWS credentials

my $queue = $sqs->GetQueue("queue url"); # create an object for accessing an old queue  

while (1) # working in an infinite loop
{    
 my @msg = $queue->ReceiveMessage( MaxNumberOfMessages => 10 ); # get the messages into @msg array, here 10 messages are retrieved in a batch

 if ( !scalar(@msg) ) # will be true if no more messages are present in the queue 
    {
  print "Probably no data in queue\n";
 }
 
 foreach my $msg (@msg) # read one by one the messages from the @msg array  
    {
  my $message = $msg->MessageBody(); # fetch the message body

  print "$message\n"; # displaying the message body on the screen

  $queue->DeleteMessage( $msg->ReceiptHandle() ); # delete the retrieved message from the queue, if required 
 }
}

$queue->Delete(); # delete the AWS queue, if required 


Output:
-------
On running the Perl script from command line, it will output on the screen, all the messages reading from the AWS queue.