AutoStatisticsUserHourlyTraffic.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\SsNode;
  4. use App\Models\User;
  5. use App\Models\UserTrafficHourly;
  6. use App\Models\UserTrafficLog;
  7. use Illuminate\Console\Command;
  8. use Log;
  9. class AutoStatisticsUserHourlyTraffic extends Command {
  10. protected $signature = 'autoStatisticsUserHourlyTraffic';
  11. protected $description = '自动统计用户每小时流量';
  12. public function handle(): void {
  13. $jobStartTime = microtime(true);
  14. $userList = User::query()->where('status', '>=', 0)->whereEnable(1)->get();
  15. foreach($userList as $user){
  16. // 统计一次所有节点的总和
  17. $this->statisticsByNode($user->id);
  18. // 统计每个节点产生的流量
  19. $nodeList = SsNode::query()->whereStatus(1)->orderBy('id')->get();
  20. foreach($nodeList as $node){
  21. $this->statisticsByNode($user->id, $node->id);
  22. }
  23. }
  24. $jobEndTime = microtime(true);
  25. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  26. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  27. }
  28. private function statisticsByNode($user_id, $node_id = 0): void {
  29. $start_time = strtotime(date('Y-m-d H:i:s', strtotime("-1 hour")));
  30. $end_time = time();
  31. $query = UserTrafficLog::query()->whereUserId($user_id)->whereBetween('log_time', [$start_time, $end_time]);
  32. if($node_id){
  33. $query->whereNodeId($node_id);
  34. }
  35. $u = $query->sum('u');
  36. $d = $query->sum('d');
  37. $total = $u + $d;
  38. $traffic = flowAutoShow($total);
  39. if($total){ // 有数据才记录
  40. $obj = new UserTrafficHourly();
  41. $obj->user_id = $user_id;
  42. $obj->node_id = $node_id;
  43. $obj->u = $u;
  44. $obj->d = $d;
  45. $obj->total = $total;
  46. $obj->traffic = $traffic;
  47. $obj->save();
  48. }
  49. }
  50. }