Enabling long polling in Amazon SQS with AWS SDK for PHP Version 3
Long polling reduces the number of empty responses by allowing Amazon SQS to wait a specified time for a message to become available in the queue before sending a response. Also, long polling eliminates false empty responses by querying all of the servers instead of a sampling of servers. To enable long polling, specify a non-zero wait time for received messages. To learn more, see SQS Long Polling.
The following examples show how to:
-
Set attributes on an Amazon SQS queue to enable long polling, using SetQueueAttributes.
-
Retrieve one or more messages with long polling using ReceiveMessage.
-
Create a long polling queue using CreateQueue.
All the example code for the AWS SDK for PHP is available here on
GitHub
Credentials
Before running the example code, configure your AWS credentials, as described in Credentials. Then import the AWS SDK for PHP, as described in Basic usage.
Set attributes on a queue to enable long polling
Imports
require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sqs\SqsClient;
Sample Code
$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->setQueueAttributes([ 'Attributes' => [ 'ReceiveMessageWaitTimeSeconds' => 20 ], 'QueueUrl' => $queueUrl, // REQUIRED ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Retrieve messages with long polling
Imports
require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sqs\SqsClient;
Sample Code
$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->receiveMessage([ 'AttributeNames' => ['SentTimestamp'], 'MaxNumberOfMessages' => 1, 'MessageAttributeNames' => ['All'], 'QueueUrl' => $queueUrl, // REQUIRED 'WaitTimeSeconds' => 20, ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }
Create a queue with long polling
Imports
require 'vendor/autoload.php'; use Aws\Exception\AwsException; use Aws\Sqs\SqsClient;
Sample Code
$queueName = "QUEUE_NAME"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->createQueue([ 'QueueName' => $queueName, 'Attributes' => [ 'ReceiveMessageWaitTimeSeconds' => 20 ], ]); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }