php-redis中文件锁的使用


public function testAction()
{
// 定义锁标识
$key = 'mylock';

// 获取锁
$is_lock = $this->lock($key, 30);

var_dump($is_lock);
if($is_lock){
echo 'get lock success<br>';
echo 'do sth..<br>';
sleep(30);
echo 'success<br>';
//释放锁
$this->unlock($key);

// 获取锁失败
}else{
echo 'request too frequently<br>';
}
}



/**
* 获取锁
* @param String $key 锁标识
* @param Int $expire 锁过期时间
* @return Boolean
*/
public function lock($key, $expire=5){
$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);
}
}

return $is_lock? true : false;
}

/**
* 释放锁
* @param String $key 锁标识
* @return Boolean
*/
public function unlock($key){
return $this->_redis->del($key);
}
posted @ 2019-11-17 16:15  queqp  阅读(311)  评论(0编辑  收藏  举报