UserTrafficAbnormalAutoWarning.php 2.3 KB

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