AutoStatisticsUserHourlyTraffic.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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(
  27. '---【' . $this->description . '】完成---,耗时' . $jobUsedTime . '秒'
  28. );
  29. }
  30. private function statisticsByNode($user_id, $node_id = 0): void
  31. {
  32. $query = UserDataFlowLog::whereUserId($user_id)->whereBetween(
  33. 'log_time',
  34. [strtotime("-1 hour"), time()]
  35. );
  36. if ($node_id) {
  37. $query->whereNodeId($node_id);
  38. }
  39. $u = $query->sum('u');
  40. $d = $query->sum('d');
  41. $total = $u + $d;
  42. if ($total) { // 有数据才记录
  43. $obj = new UserHourlyDataFlow();
  44. $obj->user_id = $user_id;
  45. $obj->node_id = $node_id;
  46. $obj->u = $u;
  47. $obj->d = $d;
  48. $obj->total = $total;
  49. $obj->traffic = flowAutoShow($total);
  50. $obj->save();
  51. }
  52. }
  53. }