UserTrafficAbnormalAutoWarning.php 2.5 KB

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