利用setnx命令的原子性
/**
* 獲取鎖
* @param String $key 鎖標識
* @param Int $expire 鎖過期時間
* @return Boolean
*/
public function lock($key, $expire=5){
//time()+$expire 如果存在返回0 不存在則設(shè)置此值并返回1
$is_lock = $this->_redis->setnx($key, time()+$expire);
// 鎖存在
if(!$is_lock){
// 判斷鎖是否過期
$lock_time = $this->_redis->get($key);
// 鎖已過期孝情,刪除鎖钩蚊,重新獲取
if(time()>$lock_time){
$this->unlock($key);
$is_lock = $this->_redis->setnx($key, time()+$expire);
}
}
//設(shè)置鎖過期時間
$this->_redis->setTimeout($key, $expire);
return $is_lock? true : false;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者