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

レッスン 13: キューとジョブ

キュードライバー (Redis、SQS、データベース)。ジョブ クラス、ディスパッチ、チェーン。ジョブのバッチ処理、レート制限。失敗したジョブ。再試行してください。 Laravel Horizo​​n モニタリング。キューの優先順位。

💻 プログラミング — レッスン 13 レッスン 13: キューとジョブ

Laravel: 基本から上級まで

パート 4: 高度な機能

xdev.asia

1. キューのセットアップ

QUEUE_CONNECTION=redis
php artisan make:job ProcessOrder

2. ジョブクラス

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. ジョブチェーンとバッチ処理

// 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. ララベルホライゾン

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

次の記事: イベント、リスナー、ブロードキャスト。