UserTrafficAbnormalAutoWarning.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Components\Helpers;
  4. use App\Components\ServerChan;
  5. use Illuminate\Console\Command;
  6. use App\Http\Models\User;
  7. use App\Http\Models\UserTrafficHourly;
  8. use Log;
  9. class UserTrafficAbnormalAutoWarning extends Command
  10. {
  11. protected $signature = 'userTrafficAbnormalAutoWarning';
  12. protected $description = '用户流量异常警告';
  13. protected static $systemConfig;
  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()->where('node_id', 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()->where('id', $vo->user_id)->first();
  37. // 通过ServerChan发微信消息提醒管理员
  38. if ($vo->totalTraffic > (self::$systemConfig['traffic_ban_value'] * 1073741824)) {
  39. $traffic = UserTrafficHourly::query()->where('node_id', 0)->where('user_id', $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->username}(ID:{$user->id})**,最近1小时**上行流量:" . flowAutoShow($traffic->totalU) . ",下行流量:" . flowAutoShow($traffic->totalD) . ",共计:" . flowAutoShow($traffic->totalTraffic) . "**。";
  41. ServerChan::send($title, $content);
  42. }
  43. }
  44. }
  45. }
  46. }