1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| <?php
namespace App\Services;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Cache;
class QueueMonitorService { protected string $statsKey = 'queue:stats';
public function getStats(): array { return [ 'queues' => $this->getQueueStats(), 'workers' => $this->getWorkerStats(), 'failed' => $this->getFailedStats(), 'throughput' => $this->getThroughput(), ]; }
protected function getQueueStats(): array { $queues = ['high', 'default', 'low']; $stats = [];
foreach ($queues as $queue) { $stats[$queue] = [ 'pending' => DB::table('jobs')->where('queue', $queue)->count(), 'delayed' => DB::table('jobs') ->where('queue', $queue) ->where('available_at', '>', now()->timestamp) ->count(), ]; }
return $stats; }
protected function getWorkerStats(): array { return Cache::get("{$this->statsKey}:workers", [ 'active' => 0, 'idle' => 0, 'total' => 0, ]); }
protected function getFailedStats(): array { $hourAgo = now()->subHour();
return [ 'total' => DB::table('failed_jobs')->count(), 'last_hour' => DB::table('failed_jobs') ->where('failed_at', '>=', $hourAgo) ->count(), ]; }
protected function getThroughput(): array { return Cache::get("{$this->statsKey}:throughput", [ 'jobs_per_minute' => 0, 'jobs_per_hour' => 0, 'avg_wait_time' => 0, ]); }
public function recordJobProcessed(string $queue, float $duration): void { $key = "{$this->statsKey}:throughput";
$stats = Cache::get($key, [ 'jobs_per_minute' => 0, 'jobs_per_hour' => 0, 'avg_wait_time' => 0, 'total_duration' => 0, 'job_count' => 0, ]);
$stats['job_count']++; $stats['total_duration'] += $duration; $stats['avg_wait_time'] = $stats['total_duration'] / $stats['job_count'];
Cache::put($key, $stats, 3600); } }
|