UserTrafficAbnormalAutoWarning.php 3.1 KB

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