AutoStatisticsUserHourlyTraffic.php 2.7 KB

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