常見應用場景,發帖,回帖,發送短信請求等,秒殺搶購等,需要限制單個用戶單位時間內的有效請求次數時使用。
/**
* 單位時間內請求次數限制。
* @return array
*/
function preCheck_frequency( $lock_key , $expire = 0 , $tag = '發帖'){
if( !$expire ) $expire = self::REQUEST_INTVER_SECONDS;
$redis = self::createRedisObj();
if( $redis->get($lock_key)){
$left_time = $redis->ttl($lock_key);
return array( "status" => false , "message" =>$expire ."秒內只允許 $tag 一次!請".$left_time."之後再嘗試");
}else {
$redis->setEx($lock_key , $expire , "1" );
return array("status"=> true , "message"=>"success");
}
}
//調用代碼。
//對單個用戶生成一個鍵值
$user_id = 1;
$key = "test_post".$user_id;
$r = preCheck_frequency($key , 10 , "發帖");
if( !$r["stauts"]){
exit( $r["message"]);
}
public static $_redis;
public static function createRedisObj(){
if( ! self::$_redis){
$redis = new Redis();
$host = "192.168.1.xx"
$port = 6379;
$redis->connect($host,$port);
$redis->select(5); //選一個庫。
self::$_redis = $redis;
}
return self::$_redis;
}