文章目录 加锁解锁 加锁 -- 判断当前资源是否被锁 -- 已加锁 if redis.call("exists",KEYS[1]) ==1 then -- 判断加锁对象是否是当前操作者 -- 加锁对象是当前对象,加锁成功 if redis.call("get",KEYS[1])==ARGV[1] then -- 参数包含过期时间 if #ARGV >=2 then -- 过期时间为空,什么也不做 if ARGV[2] ==nil then -- do nothing! -- 过期时间有效,更新锁过期时间 elseif tonumber(ARGV[2])>0 then redis.call("EXPIRE",KEYS[1],ARGV[2]) -- 过期时间<=0 设置永久有效 else redis.call("PERSIST",KEYS[1]) end end return true -- 加锁者不是当前对象,加锁失败 else return false; end -- 未加锁 else -- 加锁 redis.call("set",KEYS[1],ARGV[1]) -- 参数包含过期参数有效值(>0),设置过期时间 if (#ARGV >=2) and (ARGV[2] ~=nil or ARGV[2]>=0) then redis.call("EXPIRE",KEYS[1],ARGS[2]) end return true end 解锁 -- 判断资源是否被锁 -- 已加锁 if (redis.call("exists", KEYS[1]) == 1) then -- 判断加锁者是否是当前操作者 -- 是当前操作者加锁,解锁成功 if (redis.call("get", KEYS[1]) == ARGV[1]) then redis.call("del", KEYS[1]) return true -- 不是当前操作者加锁,解锁失败 else return false end -- 未加锁,解锁成功 else return true end