To implement long polling for AWS SQS in a Laravel application, you can use a combination of Laravel's console commands and the AWS SDK for PHP. This approach allows you to continuously poll the SQS queue without running into timeout issues that you might encounter with HTTP requests.
Here's a step-by-step guide to achieve this:
-
Install AWS SDK for PHP: First, ensure you have the AWS SDK for PHP installed. You can add it to your Laravel project using Composer:
composer require aws/aws-sdk-php -
Create a Console Command: Create a new Artisan command that will handle the long polling. You can generate a new command using the Artisan CLI:
php artisan make:command PollSQSQueue -
Implement the Command: Open the newly created command file located at
app/Console/Commands/PollSQSQueue.phpand implement the logic to poll the SQS queue.Here's an example implementation:
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Aws\Sqs\SqsClient; use Illuminate\Support\Facades\Log; class PollSQSQueue extends Command { protected $signature = 'sqs:poll'; protected $description = 'Poll the AWS SQS queue for new messages'; protected $sqsClient; protected $queueUrl; public function __construct() { parent::__construct(); $this->sqsClient = new SqsClient([ 'region' => env('AWS_DEFAULT_REGION'), 'version' => 'latest', 'credentials' => [ 'key' => env('AWS_ACCESS_KEY_ID'), 'secret' => env('AWS_SECRET_ACCESS_KEY'), ], ]); $this->queueUrl = env('AWS_SQS_QUEUE_URL'); } public function handle() { while (true) { $result = $this->sqsClient->receiveMessage([ 'QueueUrl' => $this->queueUrl, 'MaxNumberOfMessages' => 1, 'WaitTimeSeconds' => 20, // Long polling ]); if (!empty($result->get('Messages'))) { foreach ($result->get('Messages') as $message) { // Process the message $this->processMessage($message); // Delete the message from the queue $this->sqsClient->deleteMessage([ 'QueueUrl' => $this->queueUrl, 'ReceiptHandle' => $message['ReceiptHandle'], ]); } } // Sleep for a short period to avoid hitting rate limits sleep(5); } } protected function processMessage($message) { // Implement your message processing logic here Log::info('Processing message: ' . $message['Body']); } } -
Configure Environment Variables: Ensure you have the necessary AWS credentials and SQS queue URL in your
.envfile:AWS_ACCESS_KEY_ID=your-access-key-id AWS_SECRET_ACCESS_KEY=your-secret-access-key AWS_DEFAULT_REGION=your-region AWS_SQS_QUEUE_URL=your-sqs-queue-url -
Run the Command: You can run the command manually using:
php artisan sqs:pollAlternatively, you can set up a supervisor or a similar process manager to keep the command running continuously in the background.
By following these steps, you can continuously poll an AWS SQS queue in a Laravel application without running into timeout issues. The console command will keep running, checking for new messages and processing them as they arrive.