redisson分布式锁lua脚本翻译

1.获取锁

 lock入参:
keys[1]:自定义锁的key  RLock lock = redissonClient.getLock(lockKey);
argv[1]=锁的租期,默认30s  
argv[2]=锁的名称(UUID:threadId)

if(exists keys[1]==0  1.不存在key锁) then
hset keys[1] argv[2] 1  赋值 key field value-->1.1尝试获取锁
pexpire keys[1] argv[1] 过期 expire key time-->1.2设置锁过期时间
return 空;
end

if(hexists keys[1] argv[2]==1  存在Key name 的锁--》2.当前线程已获取锁) then
hincrby keys[1] argv[2] 1    -->2.1原子计数器+1  锁重入!!!
pexpire keys[1] argv[1]  过期-->2.2重置锁过期时间
return 空;
end

return pttl keys[1]-->3.返回剩余过期时间

 ps:lua脚本数组下标从1开始

2.释放锁

 unlock入参:
keys[1]:自定义锁的key  RLock lock = redissonClient.getLock(lockKey);
keys[2]:通道名称  redisson_lock__channel:{UUID:threadId}
argv[1]= publish unlock消息=0
argv[2]=锁的租期,默认30s
argv[3]=锁的名称(UUID:threadId)

if(hexists keys[1] argv[3]==0-->1.不存在key锁,直接返回) then
return 空

counter=hincrby keys[1] argv[3] -1-->2.存在锁,原子计数器-1

if(counter>0) then pexpire KEYS[1] ARGV[2]-->2.1 计数器>0,还有锁没释放,重置锁过期时间
return 0;

else -->2.2计数器=0,锁已经全部释放完毕。
del KEYS[1]-->删除key
publish KEYS[2] ARGV[1]-->发布消息 publish channel message
return 1;
end
return 空;

------------------个人能力有限,大家多交流,一起壮哉我大JAVA!------------------

如果你觉得本文对你有点帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

原文地址:https://www.cnblogs.com/dennyzhangdd/p/14550249.html