使用redis鎖解決數據接收高併發問題
$redisName='tengyi-callback-'.time().rand(1,100000);
if($this->sets($redisName,20)){
}
//在TP5的當前控制器中
/**
* @function 加鎖
* @param $key 鎖名稱
* @param $expTime 過期時間
*/
public function sets($key,$expTime)
{
//初步加鎖
$isLock = cache::setnx($key,time()+$expTime);
if($isLock) {return true;}else {
//加鎖失敗的情況下。判斷鎖是否已經存在,如果鎖存在切已經過期,那麼刪除鎖。進行重新加鎖
$val = cache::get($key);
if($val&&$val<time())
{
$this->del($key);
}
return cache::setnx($key,time()+$expTime);
}
}
//在TP5的cache.php文件中
/**
* @function 加鎖
* @param $key 鎖名稱
* @param $expTime 過期時間
*/
public static function setnx($key,$expTime)
{
return self::init()->setnx($key,time()+$expTime);
}
//在TP5的redis.php文件中
public function setnx($key,$expTime){
//初步加鎖
$isLock = $this->handler->setnx($key,time()+$expTime);
if($isLock) {return true;}else {
//加鎖失敗的情況下。判斷鎖是否已經存在,如果鎖存在切已經過期,那麼刪除鎖。進行重新加鎖
$val = $this->handler->get($key);
if($val&&$val<time())
{
$this->del($key);
}
return $this->handler->setnx($key,time()+$expTime);
}
}
有不對的地方可以留言討論已測試可以使用