|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use Illuminate\Console\Command; |
| 6 | +use App\Http\Models\User; |
| 7 | +use App\Http\Models\SsNode; |
| 8 | +use App\Http\Models\UserTrafficDaily; |
| 9 | +use App\Http\Models\UserTrafficLog; |
| 10 | +use Log; |
| 11 | + |
| 12 | +class AutoStatisticsUserDailyTrafficJob extends Command |
| 13 | +{ |
| 14 | + protected $signature = 'command:autoStatisticsUserDailyTrafficJob'; |
| 15 | + protected $description = '用户每日流量自动统计'; |
| 16 | + |
| 17 | + public function __construct() |
| 18 | + { |
| 19 | + parent::__construct(); |
| 20 | + } |
| 21 | + |
| 22 | + public function handle() |
| 23 | + { |
| 24 | + $userList = User::get(); |
| 25 | + foreach ($userList as $user) { |
| 26 | + // 统计一次所有节点的总和 |
| 27 | + $this->statisticsByNode($user->id); |
| 28 | + |
| 29 | + // 统计每个节点产生的流量 |
| 30 | + $nodeList = SsNode::get(); |
| 31 | + foreach ($nodeList as $node) { |
| 32 | + $this->statisticsByNode($user->id, $node->id); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + Log::info('定时任务:' . $this->description); |
| 37 | + } |
| 38 | + |
| 39 | + private function statisticsByNode($user_id, $node_id = 0) { |
| 40 | + $start_time = strtotime(date('Y-m-d 00:00:00', strtotime("-1 day"))); |
| 41 | + $end_time = strtotime(date('Y-m-d 23:59:59', strtotime("-1 day"))); |
| 42 | + |
| 43 | + $query = UserTrafficLog::where('user_id', $user_id)->whereBetween('log_time', [$start_time, $end_time]); |
| 44 | + |
| 45 | + if ($node_id) { |
| 46 | + $query->where('node_id', $node_id); |
| 47 | + } |
| 48 | + |
| 49 | + $u = $query->sum('u'); |
| 50 | + $d = $query->sum('d'); |
| 51 | + $total = $u + $d; |
| 52 | + $traffic = $this->flowAutoShow($total); |
| 53 | + |
| 54 | + $obj = new UserTrafficDaily(); |
| 55 | + $obj->user_id = $user_id; |
| 56 | + $obj->node_id = $node_id; |
| 57 | + $obj->u = $u; |
| 58 | + $obj->d = $d; |
| 59 | + $obj->total = $total; |
| 60 | + $obj->traffic = $traffic; |
| 61 | + $obj->save(); |
| 62 | + } |
| 63 | + |
| 64 | + // 根据流量值自动转换单位输出 |
| 65 | + private function flowAutoShow($value = 0) |
| 66 | + { |
| 67 | + $kb = 1024; |
| 68 | + $mb = 1048576; |
| 69 | + $gb = 1073741824; |
| 70 | + $tb = $gb * 1024; |
| 71 | + $pb = $tb * 1024; |
| 72 | + if (abs($value) > $pb) { |
| 73 | + return round($value / $pb, 2) . "PB"; |
| 74 | + } elseif (abs($value) > $tb) { |
| 75 | + return round($value / $tb, 2) . "TB"; |
| 76 | + } elseif (abs($value) > $gb) { |
| 77 | + return round($value / $gb, 2) . "GB"; |
| 78 | + } elseif (abs($value) > $mb) { |
| 79 | + return round($value / $mb, 2) . "MB"; |
| 80 | + } elseif (abs($value) > $kb) { |
| 81 | + return round($value / $kb, 2) . "KB"; |
| 82 | + } else { |
| 83 | + return round($value, 2) . "B"; |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments