UserTrafficAbnormalAutoWarning.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\PushNotification;
  4. use App\Models\User;
  5. use App\Models\UserHourlyDataFlow;
  6. use Illuminate\Console\Command;
  7. use Log;
  8. class UserTrafficAbnormalAutoWarning extends Command {
  9. protected $signature = 'userTrafficAbnormalAutoWarning';
  10. protected $description = '用户流量异常警告';
  11. public function handle(): void {
  12. $jobStartTime = microtime(true);
  13. // 用户流量异常警告
  14. $this->userTrafficAbnormalWarning();
  15. $jobEndTime = microtime(true);
  16. $jobUsedTime = round(($jobEndTime - $jobStartTime), 4);
  17. Log::info('---【'.$this->description.'】完成---,耗时'.$jobUsedTime.'秒');
  18. }
  19. // 用户流量异常警告
  20. private function userTrafficAbnormalWarning(): void {
  21. // 1小时内流量异常用户(多往前取5分钟,防止数据统计任务执行时间过长导致没有数据)
  22. $userTotalTrafficList = UserHourlyDataFlow::whereNodeId(0)
  23. ->where('total', '>', MB * 50)
  24. ->where('created_at', '>=', date('Y-m-d H:i:s', time() - 3900))
  25. ->groupBy('user_id')
  26. ->selectRaw("user_id, sum(total) as totalTraffic")
  27. ->get(); // 只统计100M以上的记录,加快查询速度
  28. foreach($userTotalTrafficList as $vo){
  29. $user = User::find($vo->user_id);
  30. // 推送通知管理员
  31. if($vo->totalTraffic > sysConfig('traffic_ban_value') * GB){
  32. $traffic = UserHourlyDataFlow::userRecentUsed($user->id)
  33. ->selectRaw("user_id, sum(`u`) as totalU, sum(`d`) as totalD, sum(total) as totalTraffic")
  34. ->first();
  35. PushNotification::send("流量异常用户提醒",
  36. "用户**{$user->email}(ID:{$user->id})**,最近1小时**上行流量:".flowAutoShow($traffic->totalU).",下行流量:".flowAutoShow($traffic->totalD).",共计:".flowAutoShow($traffic->totalTraffic)."**。");
  37. }
  38. }
  39. }
  40. }