使用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);
}
}
有不对的地方可以留言讨论已测试可以使用