redis+lua實現分佈式鎖

lock腳本:lock.luaredis

-- Set a lock
--  若是獲取鎖成功,則返回 1
local key     = KEYS[1]
local content = KEYS[2]
local ttl     = ARGV[1]
local lockSet = redis.call('setnx', key, content)
if lockSet == 1 then
  redis.call('pexpire', key, ttl) 
else 
  -- 若是value相同,則認爲是同一個線程的請求,則認爲重入鎖
  local value = redis.call('get', key)
  if(value == content) then
    lockSet = 1;
    redis.call('pexpire', key, ttl)
  end
end
return lockSet
  •  

unlock腳本: unlock.lualua

-- unlock key
local key     = KEYS[1]
local content = KEYS[2]
local value = redis.call('get', key)
if value == content then( 
  return redis.call('del', key);
end
return 0
相關文章
相關標籤/搜索