Home  >  Article  >  Backend Development  >  PHP+Redis/Memcache(过期机制)实现高效限制一段时间内操作次数限制逻辑

PHP+Redis/Memcache(过期机制)实现高效限制一段时间内操作次数限制逻辑

WBOY
WBOYOriginal
2016-06-20 13:03:171145browse

有时候为了限制某个用户或者某ip用户一段时间内最大操作次数,我们可能会用mysql直接记录每次的用户的记录,通过time时间字段来统计某时间段操作次数来限制,为了高效的实习类似的逻辑,我们可以使用key/value,高效完成这种逻辑。

例如实现:一个用户10分钟内最多投票5次

$redis = new Redis();
$redis_conn = $redis->connect('127.0.0.1',6379);	

if($redis_conn){
    $result = json_decode($redis->get('test'), true); 
    $result = is_array($result)?$result:array();
    
    if(count($result)<5 || ($last = array_shift($result) < time()-10*60)){
        array_push($result, time());
        $redis->setex("test", 10*60, json_encode($result));
        //echo $redis->ttl("test");
        echo &#39;投票逻辑&#39;;
    
    }else{
        echo &#39;10分钟内投票次数已达到最大5,稍后再试!&#39;;
    }
}else{
    echo &#39;Redis is gone!&#39;;
}

 


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn