首页 > 编程知识 正文

redis使用lua脚本加锁和解锁,Redis实现分布式锁

时间:2023-05-04 17:52:09 阅读:22447 作者:2737

//*

//*

类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 {

返回假;

}

}

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。