Copied!
Laravel

How to integrate Amazon SQS in Laravel for queue mechanism

amazon-sqs.jpg
Umar Saeed
Aug 12, 2023 . 713 views

Table Of Contents

 

What is Amazon SQS

Amazon Simple Queue Service (Amazon SQS) is a fully managed message queuing service provided by Amazon Web Services (AWS). It enables you to decouple the components of your applications so that they can communicate asynchronously. With SQS, you can send, store, and receive messages between distributed software components and microservices, without these components needing to be available or operational at the same time.

Installation in Laravel

01: Create Laravel project

composer create-project --prefer-dist laravel/laravel LaravelSQSExample

02: Install AWS SDK:

composer require aws/aws-sdk-php

03: Setup AWS Credentials:

set the following environment variables in your .env file:

AWS_ACCESS_KEY_ID=your_access_key
AWS_SECRET_ACCESS_KEY=your_secret_key
AWS_DEFAULT_REGION=us-east-1
         

04: Configure Queue Connection:

in config/queue.php

'sqs' => [
  'driver' => 'sqs',
  'key' => env('AWS_ACCESS_KEY_ID'),
  'secret' => env('AWS_SECRET_ACCESS_KEY'),
  'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
  'queue' => env('SQS_QUEUE', 'default'),
  'suffix' => env('SQS_SUFFIX'),
  'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
  'after_commit' => false,
],
         

05: Create a Queue:

In your .env file, add the queue name you want to use::

AWS_SQS_QUEUE_NAME=your-queue-name //i.e message_queue

06: Send Messages to the Queue:

make a new controller

php artisan make:controller SQSController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Queue;

class SQSController extends Controller
{
    public function sendMessage(Request $request)
    {
      $message = $request->input('message');
      
      Queue::connection('sqs')->push(function ($job) use ($message) {
            // Process the message or perform some task here...
            
            $job->delete();
      });
      Or
      // Queue::connection('sqs')->pushRaw($message);
      return response()->json(['message' => 'Message sent to the queue']);
    }
}

         

07: Receive Messages from the Queue:

Create a new Artisan command to receive messages from the SQS queue:

php artisan make:command ProcessSQSMessages

Open the generated ProcessSQSMessages.php file in the app/Console/Commands directory and modify the handle method to process the messages:

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Queue;

class ProcessSQSMessages extends Command
{
  protected $signature = 'sqs:process-messages';
  
  protected $description = 'Process messages from the SQS queue';

  public function handle()
  {
      Queue::connection('sqs')->pop(function ($job) {
            // Process the received message...
            $job->delete();
      });
  }
}

08: Run the Command

php artisan sqs:process-messages
 

Customize Queue Configuration

You can customize queue configurations based on your needs. For example, you might want to set the maximum number of times a job should be attempted before being marked as failed. Edit the config/queue.php file:

'connections' => [
    'sqs' => [
      // ...
      'max_attempts' => 3, // Set the maximum number of attempts
    ],
],
         
 

Implement Advanced Features

Amazon SQS offers features like delayed queues and job prioritization. Let's explore these features:

01: Delayed Queues:

You can use delayed queues to schedule messages to be delivered after a specific delay. Here's how you can use it:

Queue::connection('sqs')->later(60, function ($job) use ($message) {
    $this->processMessage($message);
    $job->delete();
});
   

This will delay processing the message for 60 seconds.

02: Job Prioritization:

You can prioritize jobs to control their order of execution. Higher-priority jobs are processed first. Set the priority option when pushing a job:

Queue::connection('sqs')->push(function ($job) use ($message) {
    $this->processMessage($message);
    $job->delete();
}, $message, null, 'high');
         

In this example, the job has a priority of 'high'.

Conclusion

By following these steps you should be use Amazon SQS in your Laravel project. if you still have question comment down below.

13 Shares