php实现防刷和监控功能

Php   2025-12-03 10:53   59   0  
/**
 * 智能防刷系统 - 让羊毛党无功而返
 */
class AntiSpamSystem 
{
    /**
     * 滑动窗口限流 - 比保安还严格
     */
    public function checkSlidingWindow($userId, $action)
    {
        $key = "window:{$userId}:{$action}";
        $now = time();

        // Redis的ZSET:程序员的瑞士军刀
        $this->redis->zremrangebyscore($key, 0, $now - 300); // 清理5分钟前的记录
        $currentRequests = $this->redis->zcard($key); // 统计当前窗口请求数

        if ($currentRequests >= 10) {
            return [
                'allowed' => false,
                'message' => '兄弟,手速这么快去打游戏吧!'
            ];
        }

        // 记录本次请求
        $this->redis->zadd($key, $now, uniqid());
        $this->redis->expire($key, 300);

        return ['allowed' => true, 'message' => '通过检测,继续吧~'];
    }

    /**
     * 行为分析 - AI防刷(简化版)
     */
    public function analyzeBehavior($userId, $sessionDuration)
    {
        // 如果session时间太短,可能在刷接口
        if ($sessionDuration < 5) {
            $suspiciousKey = "suspicious:{$userId}";
            $count = $this->redis->incr($suspiciousKey);
            $this->redis->expire($suspiciousKey, 3600);

            if ($count > 8) {
                return [
                    'suspicious' => true,
                    'message' => '检测到异常行为,请稍后再试'
                ];
            }
        }

        return ['suspicious' => false];
    }
}
/**
 * 性能监控系统 
 */
class PerformanceMonitor 
{
    /**
     * API性能监控 - 实时掌握系统脉搏
     */
    public function monitorApi($endpoint, $startTime, $endTime, $success = true)
    {
        $duration = ($endTime - $startTime) * 1000; // 毫秒

        // 记录到Redis时序数据
        $hourKey = "perf:" . date('Y-m-d-H');

        $this->redis->pipeline(function($pipe) use ($hourKey, $endpoint, $duration, $success) {
            $pipe->hincrby($hourKey, "{$endpoint}:count", 1);
            $pipe->hincrby($hourKey, "{$endpoint}:total_time", $duration);

            if (!$success) {
                $pipe->hincrby($hourKey, "{$endpoint}:errors", 1);
            }

            $pipe->expire($hourKey, 86400); // 保存24小时
        });

        // 如果响应时间超过1秒,立即告警
        if ($duration > 1000) {
            $this->sendAlert("🚨 API响应缓慢警告", [
                'endpoint' => $endpoint,
                'duration' => $duration . 'ms',
                'time' => date('Y-m-d H:i:s'),
                'message' => '该接口可能需要优化了'
            ]);
        }
    }

    /**
     * 系统资源监控 - 比体检还全面
     */
    public function monitorSystem()
    {
        $cpu = sys_getloadavg()[0];
        $memory = memory_get_usage(true) / 1024 / 1024; // MB

        $metrics = [
            'cpu_load' => $cpu,
            'memory_mb' => $memory,
            'timestamp' => time()
        ];

        // 保存监控数据
        $key = "metrics:" . date('Y-m-d-H-i');
        $this->redis->hmset($key, $metrics);
        $this->redis->expire($key, 86400);

        // CPU负载超过80%就告警
        if ($cpu > 0.8) {
            $this->sendAlert("🔥 CPU负载过高", [
                'cpu_load' => $cpu,
                'memory_usage' => $memory . 'MB',
                'message' => '服务器可能需要关爱了'
            ]);
        }
    }

    private function sendAlert($title, $data)
    {
        // 可以发钉钉、企业微信、邮件等
        // 这里简化处理
        error_log("ALERT: {$title} - " . json_encode($data));

        // 如果是生产环境,这里会发送真实告警
        if (env('APP_ENV') === 'production') {
            $this->sendToWechat($title, $data);
        }
    }
}