<?php
session_start();
class locks{
private $redis;
protected $lockid;//记录客户端加锁的ID
public function __construct($obj){
$this->redis = $obj;
}
/**
* @param string $name 参数名
* @param int $exp 过期时间
* @param int $retry 重复次数
* @param int $sleep 等待时间
*/
public function lock($name = 'lock',$exp = 5,$retry = 5 , $sleep = 1){
$result = false;
while ($retry-- >= 0){
$value = session_create_id();
$result = $this->redis->set( $name , $value , ['NX' , 'EX'=>$exp] );
if ($result) {
$this->lockid[$name] = $value;
break;
}
echo '尝试获取锁' . $retry;
sleep($sleep);
}
return $result;
}
/**
* @param $name
* @return mixed
* 删除锁
*/
public function unlock( $name ){
if ( isset($this->lockid[$name]) ) {
$val = $this->redis->get( $name );
if ($val == $this->lockid[$name] ) {
return $this->redis->del( $name );
}
}
return false;
}
}
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$obj = new locks($redis);
var_dump($obj->lock());