原理是通过使用redis存储每个用户的访问次数 在这里我设置的是10 次 ,当用户访问时 传递用户id 每次请求次数都会增加一次 ,每次判断当达到十次时就会返回不允许访问。
PHP
//测试调用
function text()
{
$this->restrict(1);
}
//限制函数
public function restrict($uid)
{
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$key = 'user:1:api_count' . $uid;
//限制次数为10
$limit = 10;
// $check = $redis->exists($key);
$check = 1;
if ($check) {
$redis->incr($key);
$count = $redis->get($key);
if ($count > $limit) {
exit('your have too many request');
}
} else {
$redis->incr($key);
//限制时间为60秒
$redis->expire($key, 60);
}
$count = $redis->get($key);
echo 'You have ' . $count . ' request';
}