UserTrafficAbnormalAutoWarning.php 2.1 KB

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