Sqs client

This page contains examples with the Sqs client. See the client introduction for a more detailed description how to use a client. You may also want to consider the authentication documentation to understand the many ways you can authenticate with AWS.

The Sqs package could be installed with Composer.

composer require async-aws/sqs

A new client object may be instantiated by:

use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient();

The authentication parameters is read from the environment by default. You can also specify a AWS access id and secret:

use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient([ 'accessKeyId' => 'my_access_key', 'accessKeySecret' => 'my_access_secret', 'region' => 'eu-central-1', ]);

For all available options, see the configuration reference.


Send a message

use AsyncAws\Sqs\Input\GetQueueUrlRequest; use AsyncAws\Sqs\Input\SendMessageRequest; use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(); $queueUrl = $sqs->getQueueUrl(new GetQueueUrlRequest([ 'QueueName' => 'invoices-queue', ]))->getQueueUrl(); $result = $sqs->sendMessage(new SendMessageRequest([ 'QueueUrl' => $queueUrl, 'MessageBody' => 'invoiceId: 1337', ])); echo $result->getMessageId();

Receive Messages

use AsyncAws\Sqs\Input\ChangeMessageVisibilityRequest; use AsyncAws\Sqs\Input\DeleteMessageRequest; use AsyncAws\Sqs\Input\GetQueueUrlRequest; use AsyncAws\Sqs\Input\ReceiveMessageRequest; use AsyncAws\Sqs\SqsClient; $sqs = new SqsClient(); $queueUrl = $sqs->getQueueUrl(new GetQueueUrlRequest([ 'QueueName' => 'invoices-queue', ]))->getQueueUrl(); $result = $sqs->receiveMessage(new ReceiveMessageRequest([ 'QueueUrl' => $queueUrl, 'WaitTimeSeconds' => 20, 'MaxNumberOfMessages' => 5, ])); foreach ($result->getMessages() as $message) { try { // Do something with message // ... // When finished, delete the message $sqs->deleteMessage(new DeleteMessageRequest([ 'QueueUrl' => $queueUrl, 'ReceiptHandle' => $message->getReceiptHandle(), ])); } catch (\Exception $e) { // Optional : Set the visibility to 0 to be instantaneously requeued $sqs->changeMessageVisibility(new ChangeMessageVisibilityRequest([ 'QueueUrl' => $queueUrl, 'ReceiptHandle' => $message->getReceiptHandle(), 'VisibilityTimeout' => 0, ])); } }

The source code to this page is found on GitHub.