//*
//*
类redis lock {
//*
privateconstredis _ lock _ key _ prefix=' redis 3360 lock : ';
//*
私有$锁定名称=[ ];
//*
私有$ redis object=null;
//*
私有静态$自助=null;
//*
protectedconstredis _ lock _ prefix=' redis 3360 lock : ';
//*
隐私函数_ _ construct (
}
//*
私有函数_ _ clone (
}
//*
publicstaticfunctiongetinstance ($ redis object )。
if (自:3360 $ self==null ({
$self=new self (;
$self-redisObject=$redisObject;
self:$self=$self;
}
return self:$self;
}
//*
publicfunctionlock(string$name,int $expire=5,int $retryTimes=10,$sleep=10000 ) {
$oj8k=false;
$retrytimes=max($retrytimes,1 );
$ key=self :3360 redis _ lock _ key _ prefix.$ name;
wile ($恢复时间----0 ) {
$kval=microtime(true ) $expire;
$OJ8K=$this-getlock($key、$expire、$kVal ); //锁门
if($OJ8K ) {
$this-lockedNames[$key]=$kVal;
布雷克;
}
usleep($sleep;
}
返回$ oj8k;
}
//*
隐私功能getlock ($ key、$expire、$value ) {
$script=
local key=KEYS[1]
local value=ARGV[1]
局部TTL=argv [2]
if(redis.call('setNX ',key,value )==1) then
returnRedis.call(Expire ),key,ttl ) ) )。
elseif(redis.call(TTL,key )==-1 ) then
returnRedis.call(Expire ),key,ttl ) ) )。
结束
返回0
LUA;
返回$ this-execluascript ($ script,[$key,$value,$expire] );
}
//*
publicfunctionunlock (string $ name ) {
$script=
local key=KEYS[1]
local value=ARGV[1]
if(Redis.call(Exists ),key )==1andRedis.call ) (get ),key )==value ) ) ) )。
陈真
returnredis.call('del ',key ) )。
结束
返回0
LUA;
$ key=self :3360 redis _ lock _ key _ prefix.$ name;
if (isset ($ this-locked names [ $ key ] ) )。
$ val=$ this -锁定名称[ $ key ];
返回$ this-execluascript ($ script,[$key,$val];
}
返回假;
}
//*
privatefunctionexecluascript ($ script,array $params,$keyNum=1) {
$ hash=$ this-redis object-script (' load ',$script );
返回$ this-redis object-eval sha ($ hash、$params、$keyNum );
}
//*
publicfunction run (callable $ func、string $name、int $expire=5、int $retryTimes=10、$sleep=10000 ) {
if($this-lock ) $name、$expire、$retryTimes、$sleep ) }
try {
call_user_func($func;
}catch(exception$e ) {
throw $e;
} finally {
$this-unlock($name );
}
返回真;
} else {
返回假;
}
}
}