Implementeer Geavanceerde Laravel Queue Monitoring en Beheer
description
Met deze prompt kan de gebruiker een betrouwbaar en inzichtelijk queuebeheer opzetten, waardoor wachtrijprocessen efficiënter en stabieler worden. Het helpt bij het voorkomen van job-failures door automatische retries en biedt realtime inzicht via dashboards, wat beter is dan alleen basis queueconfiguraties.
prompt
Help me bij het opzetten van een geavanceerd queue monitoring en beheersysteem in mijn Laravel applicatie. Ik wil inzicht krijgen in de status van mijn wachtrijen, taken kunnen prioriteren, en automatisch falende jobs kunnen herstarten. Specificeer welke queue ...
try_prompt
generate_helper
disclaimerOnPageApi
tags
ai_answers
provider: openai
model: gpt-4.1-nano
Natuurlijk! Hier is een stapsgewijze gids voor het opzetten van een geavanceerd wachtrijmonitorings- en beheersysteem in je Laravel applicatie:
1. Queue Drivers Instellen
---------------------------
Gebruik meerdere queue drivers voor flexibiliteit:
- Redis: voor snelle, real-time verwerking en monitoring.
- Database: voor persistente opslag en historische analyses.
Configureer je `config/queue.php`:
```php
'connections' => [
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
'block_for' => null,
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
],
```
2. Monitoring en Dashboard Integratie
-------------------------------------
Gebruik bestaande tools of bouw je eigen dashboard:
a) Laravel Telescope (voor basis monitoring)
- Installeer via Composer:
```
composer require laravel/telescope
php artisan telescope:install
php artisan migrate
```
- Telescope biedt inzicht in queued jobs, failed jobs, en meer.
b) Realtime Monitoring met Laravel WebSockets of third-party tools:
- Overweeg het integreren van Laravel WebSockets (via `beyondcode/laravel-websockets`) voor realtime dashboards.
- Of gebruik tools zoals Grafana in combinatie met Redis (metrics verzamelen via Prometheus).
c) Eigen Dashboard:
- Bouw een Blade of Vue.js interface die via API endpoints de status ophaalt.
- Gebruik Laravel's cache of Redis om queue-statistieken op te slaan en weer te geven.
3. Prioriteren van Taken
------------------------
- Stel prioriteiten in door verschillende queues te gebruiken (bijv. `high`, `medium`, `low`).
- Verwerk hogere prioriteit queues vaker of met meer workers:
```bash
php artisan queue:work redis --queue=high,medium,low --tries=3
```
- Of dynamisch prioriteiten aanpassen door jobs in verschillende queues te plaatsen.
4. Automatisch Herstarten van Failing Jobs
------------------------------------------
- Laravel herstart automatisch jobs die falen, afhankelijk van je retry-configuratie.
- Gebruik `retry_after` en `max_attempts` in je queue-configuratie.
- Voor meer controle:
- Implementeer een `failed` callback:
```php
Queue::failing(function (JobFailed $event) {
// Log of notify over failure
});
```
- Gebruik Laravel Horizon (voor Redis) voor uitgebreide herstelfuncties en failover management.
5. Notificaties bij Fouten
--------------------------
- Configureer Laravel's `Failed Jobs` notificaties:
- Maak een Mailable die je wilt sturen bij elke job failure.
- Voeg in `app/Exceptions/Handler.php` toe:
```php
public function failed(JobFailed $event)
{
Mail::to('jouw-email@example.com')->send(new JobFailedNotification($event));
}
```
- Of gebruik Laravel Horizon's ingebouwde failover notificaties.
6. Retry-Logica Configureren
-----------------------------
- Stel `tries` en `timeout` in je jobs:
```php
public $tries = 5;
public $timeout = 120; // seconden
```
- Gebruik `retry_after` in `queue.php`.
- Voor complexe retries kun je een custom retry-logica implementeren door `failed` en `retry` methods in je jobs.
7. Samenvatting
----------------
- Gebruik Redis en Database queues voor flexibiliteit.
- Implementeer Laravel Horizon voor uitgebreide monitoring en beheer.
- Configureer notificaties via Laravel's mail systeem.
- Bouw of integreer dashboards voor realtime inzicht.
- Stel prioriteiten door meerdere queues te gebruiken.
- Pas retry- en failover-logica toe om job-uitval te minimaliseren.
Met deze aanpak heb je een krachtig en overzichtelijk systeem voor queue monitoring en management in je Laravel applicatie.
provider: deepseek
model: deepseek-chat
Zeker, ik help je graag met het opzetten van een geavanceerd queue monitoring systeem in Laravel. Hier is een complete handleiding:
## Queue Drivers Configuratie
Configureer je `.env` bestand voor beide drivers:
```env
QUEUE_CONNECTION=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
```
In `config/queue.php` configureer je beide connections:
```php
'connections' => [
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 90,
'block_for' => null,
],
],
```
## Job Failure Notificaties - E-mail
### 1. Failed Job Table aanmaken
```bash
php artisan queue:failed-table
php artisan migrate
```
### 2. Failure Notificatie configureren
Maak een notification class:
```bash
php artisan make:notification JobFailedNotification
```
```php
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
class JobFailedNotification extends Notification
{
use Queueable;
protected $job;
protected $exception;
public function __construct($job, $exception)
{
$this->job = $job;
$this->exception = $exception;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->error()
->subject('Job Failure: ' . get_class($this->job))
->line('Een job is mislukt in de queue.')
->line('Job: ' . get_class($this->job))
->line('Fout: ' . $this->exception->getMessage())
->action('Bekijk Failed Jobs', url('/horizon/failed'));
}
}
```
### 3. Event Listener registreren
In `App\Providers\EventServiceProvider`:
```php
protected $listen = [
\Illuminate\Queue\Events\JobFailed::class => [
\App\Listeners\HandleFailedJob::class,
],
];
```
Maak de listener:
```bash
php artisan make:listener HandleFailedJob
```
```php
<?php
namespace App\Listeners;
use Illuminate\Queue\Events\JobFailed;
use App\Notifications\JobFailedNotification;
use Illuminate\Support\Facades\Notification;
class HandleFailedJob
{
public function handle(JobFailed $event)
{
$notifiables = config('queue.failed_notifications');
Notification::send($notifiables, new JobFailedNotification(
$event->job, $event->exception
));
}
}
```
## Realtime Monitoring Dashboard
### 1. Laravel Horizon installeren
```bash
composer require laravel/horizon
php artisan horizon:install
php artisan migrate
```
### 2. Horizon configureren
In `config/horizon.php`:
```php
'environments' => [
'production' => [
'supervisor-1' => [
'connection' => 'redis',
'queue' => ['default', 'high', 'low'],
'balance' => 'auto',
'processes' => 10,
'tries' => 3,
],
],
],
// Notificaties configureren
'notifications' => [
'wait' => [
'enabled' => true,
'threshold' => 60,
],
],
```
### 3. Supervisors configureren voor prioritering
```php
'supervisors' => [
[
'connection' => 'redis',
'queue' => ['high', 'default', 'low'],
'balance' => 'simple',
'processes' => 5,
'tries' => 3,
],
],
```
## Geavanceerde Retry Logica
### 1. Custom Job met geavanceerde retry
```php
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class AdvancedJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 5;
public $maxExceptions = 3;
public $backoff = [1, 5, 10, 30, 60]; // Progressive backoff in minutes
public function handle()
{
// Je job logica hier
}
public function failed(\Throwable $exception)
{
// Custom failure handling
\Log::error('Job failed after retries: ' . $exception->getMessage());
}
public function retryUntil()
{
return now()->addMinutes(10);
}
}
```
### 2. Custom Queue Worker met retry logica
Maak een custom command:
```bash
php artisan make:command CustomQueueWorker
```
```php
<?php
namespace App\Console\Commands;
use Illuminate\Queue\Worker;
use Illuminate\Queue\WorkerOptions;
use Illuminate\Contracts\Queue\Job;
class CustomQueueWorker extends Worker
{
protected function process($connectionName, Job $job, WorkerOptions $options)
{
try {
return parent::process($connectionName, $job, $options);
} catch (\Throwable $e) {
$this->handleJobException($connectionName, $job, $options, $e);
// Custom retry logica
if ($job->attempts() < $job->maxTries()) {
$delay = $this->calculateBackoff($job->attempts());
$job->release($delay);
}
}
}
protected function calculateBackoff($attempts)
{
$backoff = [0, 60, 300, 600, 1800]; // seconds
return $backoff[$attempts] ?? end($backoff);
}
}
```
## Monitoring Endpoints
### 1. Health Check Route
```php
Route::get('/queue/health', function () {
return response()->json([
'redis_connected' => \Illuminate\Support\Facades\Redis::ping(),
'queue_size' => \Illuminate\Support\Facades\Queue::size(),
'failed_jobs' => \Illuminate\Support\Facades\DB::table('failed_jobs')->count(),
]);
});
```
### 2. Dashboard Routes
```php
Route::get('/queue/dashboard', function () {
$stats = [
'pending' => \Illuminate\Support\Facades\Queue::size(),
'failed' => \Illuminate\Support\Facades\DB::table('failed_jobs')->count(),
'processed' => \Cache::get('queue_processed', 0),
];
return view('queue-dashboard', compact('stats'));
});
```
## Gebruik
### Jobs dispatchen met prioriteit:
```php
AdvancedJob::dispatch()->onQueue('high');
AdvancedJob::dispatch()->onQueue('low')->delay(now()->addMinutes(5));
```
### Horizon starten:
```bash
php artisan horizon
```
### Monitoring:
- Horizon Dashboard: `/horizon`
- Queue Health: `/queue/health`
- Custom Dashboard: `/queue/dashboard`
Dit systeem geeft je complete controle over je queues met realtime monitoring, geavanceerde retry logica, en automatische e-mail notificaties bij failures.