Chuyển đến nội dung chính

Lesson 13: Queues & Jobs

Queue drivers (Redis, SQS, Database). Job classes, dispatching, chaining. Job batching, rate limiting. Failed jobs, retry. Laravel Horizon monitoring. Queue priorities.

💻 Programming — Lesson 13 Lesson 13: Queues & Jobs

Laravel: From Basics to Advanced

Part 4: Advanced Features

xdev.asia

1. Queue Setup

QUEUE_CONNECTION=redis
php artisan make:job ProcessOrder

2. Job Classes

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessOrder implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $backoff = 60;
    public int $timeout = 120;

    public function __construct(
        public readonly Order $order,
    ) {}

    public function handle(): void
    {
        // Process payment
        PaymentService::charge($this->order);
        // Send confirmation
        $this->order->user->notify(new OrderConfirmation($this->order));
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('Order processing failed', [
            'order_id' => $this->order->id,
            'error' => $exception->getMessage(),
        ]);
    }
}

// Dispatch
ProcessOrder::dispatch($order);
ProcessOrder::dispatch($order)->onQueue('high');
ProcessOrder::dispatch($order)->delay(now()->addMinutes(5));

3. Job Chaining & Batching

// Chaining — thực hiện tuần tự
Bus::chain([
    new ProcessPayment($order),
    new SendInvoice($order),
    new UpdateInventory($order),
])->dispatch();

// Batching — thực hiện song song
$batch = Bus::batch([
    new ProcessImage($image1),
    new ProcessImage($image2),
    new ProcessImage($image3),
])->then(function (Batch $batch) {
    Log::info('All images processed!');
})->catch(function (Batch $batch, \Throwable $e) {
    Log::error('Batch failed: ' . $e->getMessage());
})->dispatch();

4. Laravel Horizon

composer require laravel/horizon
php artisan horizon:install
php artisan horizon
// config/horizon.php
'environments' => [
    'production' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['high', 'default', 'low'],
            'balance' => 'auto',
            'maxProcesses' => 10,
            'tries' => 3,
        ],
    ],
],
# Failed jobs
php artisan queue:failed
php artisan queue:retry all
php artisan queue:flush

Next article: Events, Listeners & Broadcasting.