AutoStatisticsUserHourlyTraffic.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\Node;
  4. use App\Models\User;
  5. use App\Models\UserDataFlowLog;
  6. use App\Models\UserHourlyDataFlow;
  7. use Illuminate\Console\Command;
  8. use Log;
  9. class AutoStatisticsUserHourlyTraffic extends Command
  10. {
  11. protected $signature = 'autoStatisticsUserHourlyTraffic';
  12. protected $description = '自动统计用户每小时流量';
  13. public function handle(): void
  14. {
  15. $jobStartTime = microtime(true);
  16. foreach (User::activeUser()->get() as $user) {
  17. // 统计一次所有节点的总和
  18. $this->statisticsByNode($user->id);
  19. // 统计每个节点产生的流量
  20. foreach (Node::whereStatus(1)->orderBy('id')->get() 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. {
  30. $query = UserDataFlowLog::whereUserId($user_id)->whereBetween('log_time', [strtotime("-1 hour"), time()]);
  31. if ($node_id) {
  32. $query->whereNodeId($node_id);
  33. }
  34. $u = $query->sum('u');
  35. $d = $query->sum('d');
  36. $total = $u + $d;
  37. if ($total) { // 有数据才记录
  38. $obj = new UserHourlyDataFlow();
  39. $obj->user_id = $user_id;
  40. $obj->node_id = $node_id;
  41. $obj->u = $u;
  42. $obj->d = $d;
  43. $obj->total = $total;
  44. $obj->traffic = flowAutoShow($total);
  45. $obj->save();
  46. }
  47. }
  48. }