PHP对 API 访问的限制和监控

发布时间 2023-03-29 09:39:39作者: loganfan

API访问频率限制简单处理

$ip="127.0.0.1";
$api = "";
$allow_num = 5;
$allow_time = 60;

function check_allow($allow_num,$allow_time,$ip,$api=""){
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $api_key = md5($api.$ip);
    $redis->lpush($api_key,time()); //lpush 头部插入
    //llen 列表key 的长度
    if($redis->llen($api_key)>$allow_num){
        $old_time = $redis->rpop($api_key);//rpop 移除列表的最后一个元素
        if(time()-$old_time>$allow_time){
            return true;
        }
        return false;
    }
    return true;
}

function check_num($allow_num,$allow_time,$ip,$api=""){
	$redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    // 测试key
    $api_key = md5($api.$ip);
    //不存在key
	if (!$redis->get($api_key)){
		$redis->set($api_key, 0);
		$redis->expire($api_key, $allow_time);
	}
	//访问频率监控
	$accessCount = $redis->incr($api_key);
	if ($accessCount > $count) {
		return false;
		//访问超过限制次数
	} else {
		//剩余时间
		$remainingTime = $redis->ttl($api_key);
		return true;
	}
}