redission的可重入锁

本文介绍了一种使用Lua脚本在Redis中实现可重入锁的方法,并提供了加锁、解锁及自动续期的具体脚本实现。加锁脚本能够返回剩余时间,解锁脚本确保了锁的安全释放。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

redission加锁的lua脚本(实现了可重入),加锁失败则返回当前的key剩余时间。

if (redis.call('exists', KEYS[1]) == 0) then 
 redis.call('hincrby', KEYS[1], ARGV[2], 1); 
 redis.call('pexpire', KEYS[1], ARGV[1]);
 return nil; 
end; 
if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then 
  redis.call('hincrby', KEYS[1], ARGV[2], 1); 
  redis.call('pexpire', KEYS[1], ARGV[1]); 
  return nil; 
end; 
return redis.call('pttl', KEYS[1]);

执行逻辑:判定hash以及hash中的key是否存在,如果不存在则直接加锁,存在则原来基础上+1;

unlock的lua脚本:

if (redis.call('hexists', KEYS[1], ARGV[3]) == 0) then 
 return nil;
end; 
local counter = redis.call('hincrby', KEYS[1], ARGV[3], -1);
if (counter > 0) then 
 redis.call('pexpire', KEYS[1], ARGV[2]); 
 return 0; 
else 
 redis.call('del', KEYS[1]); 
 redis.call('publish', KEYS[2], ARGV[1]); 
 return 1; 
end; 
return nil;

解释:如果不存在则直接返回nil(类似java的null);存在则直接-1,结果值大于0则重新设置过期时间,小于0则删除key。(注意其中有publish这段,通过这个移除自动续期任务)

自动续期脚本:

if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then
 redis.call('pexpire', KEYS[1], ARGV[1]); 
 return 1; 
end; 

return 0

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值