AWS SDK for PHP
Developer Guide

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, you must specify a non-zero wait time for received messages. To learn more, see SQS Long Polling.

The following examples show how to:

All the example code for the AWS SDK for PHP Version 3 is available here on GitHub.

Credentials

Before running the example code, configure your AWS credentials, as described in Credentials for the AWS SDK for PHP Version 3. Then import the AWS SDK for PHP, as described in Basic Usage Patterns of the AWS SDK for PHP Version 3.

Set Attributes on a Queue to Enable Long Polling

Imports

require 'vendor/autoload.php'; use Aws\Sqs\SqsClient; use Aws\Exception\AwsException;

Sample Code

$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->setQueueAttributes(array( '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\Sqs\SqsClient; use Aws\Exception\AwsException;

Sample Code

$queueUrl = "QUEUE_URL"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->receiveMessage(array( '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\Sqs\SqsClient; use Aws\Exception\AwsException;

Sample Code

$queueName = "QUEUE_NAME"; $client = new SqsClient([ 'profile' => 'default', 'region' => 'us-west-2', 'version' => '2012-11-05' ]); try { $result = $client->createQueue(array( 'QueueName' => $queueName, 'Attributes' => array( 'ReceiveMessageWaitTimeSeconds' => 20 ), )); var_dump($result); } catch (AwsException $e) { // output error message if fails error_log($e->getMessage()); }