You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I've found a solution: Instead of DEL in Thread 2, I decided to use: SETNX "id:1" "" with empty value EXPIRE "id:1" 0
Then in EXEC (Thread 1) we'll see error since key "id:1" was modified Thread 3 doesn't GET data by "id:1" since expire == 0 (+double checking (in APP) on empty string "")
LUA:
-- KEYS[1] data key
-- ARGV[1] version fieldname
-- ARGV[2] new version value
-- ARGV[3] data fieldname
-- ARGV[4] data
-- ARGV[5] old version value
local oldver=redis.call('HGET',KEYS[1],ARGV[1])
if oldver then
if tonumber(oldver)~=tonumber(ARGV[5]) then
-- Get and return new values
return redis.call('HMGET',KEYS[1],ARGV[1],ARGV[3])
end
end
-- Set value when there is no conflict
redis.call('HMSET',KEYS[1],ARGV[1],ARGV[2],ARGV[3],ARGV[4])
return redis.status_reply('OK')
Thanks @eyjian. Could we use CAS without LUA scripting?
Since we are monitoring KEY via WATCH. Logically, everything what would touch my KEY should show me in EXEC of my transaction.
If another thread tries to DEL key (no matter exist or not), better to know that someone changed our key. I wonder if it's correct situation.
Activity
[-]How to use check-and-set (CAS) [/-][+]Using check-and-set (CAS) [/+]Stashchenko commentedon Mar 12, 2019
I've found a solution: Instead of DEL in Thread 2, I decided to use:
SETNX "id:1" ""with empty valueEXPIRE "id:1" 0Then in
EXEC(Thread 1) we'll see error since key "id:1" was modifiedThread 3 doesn't GET data by "id:1" since expire == 0 (+double checking (in APP) on empty string "")
eyjian commentedon Apr 2, 2019
LUA:
-- KEYS[1] data key
-- ARGV[1] version fieldname
-- ARGV[2] new version value
-- ARGV[3] data fieldname
-- ARGV[4] data
-- ARGV[5] old version value
local oldver=redis.call('HGET',KEYS[1],ARGV[1])
if oldver then
if tonumber(oldver)~=tonumber(ARGV[5]) then
-- Get and return new values
return redis.call('HMGET',KEYS[1],ARGV[1],ARGV[3])
end
end
-- Set value when there is no conflict
redis.call('HMSET',KEYS[1],ARGV[1],ARGV[2],ARGV[3],ARGV[4])
return redis.status_reply('OK')
Stashchenko commentedon Apr 2, 2019
Thanks @eyjian. Could we use CAS without LUA scripting?
Since we are monitoring KEY via WATCH. Logically, everything what would touch my KEY should show me in EXEC of my transaction.
If another thread tries to DEL key (no matter exist or not), better to know that someone changed our key. I wonder if it's correct situation.
sundb commentedon Oct 28, 2025
Close via #14435