In redis, how do I delete one key and get its value at the same time, and, most import, it is executed in one command so it is thread safe.
Update 2021: as of redis v 6.2.0, you can use GETDEL
There's no single command. You can either write a Lua script or execute a transaction. A transaction would simply look like:
127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> MULTI
OK
127.0.0.1:6379> GET foo
QUEUED
127.0.0.1:6379> DEL foo
QUEUED
127.0.0.1:6379> EXEC
1) "bar"
2) (integer) 1
Using a Lua script
127.0.0.1:6379> SET foo bar
OK
127.0.0.1:6379> EVAL "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x" 1 foo
"bar"
127.0.0.1:6379> GET foo
(nil)
Both operate the same, but with Lua script, the script can be cached and there's no need to repeat the whole code the next time you want to call it. We can use SCRIPT LOAD that caches the scripts and returns a unique id of it to be used as a function name for subsequent calls (Most clients abstract this transparently) e.g.
127.0.0.1:6379> SCRIPT LOAD "local x = redis.call('GET', KEYS[1]); redis.call('DEL', KEYS[1]); return x"
"89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7"
127.0.0.1:6379> SET foo bar
OK
# Now we use the returned SHA of the script to call it without parsing it again:
127.0.0.1:6379> EVALSHA 89d675c84cf3bd6b3b38ab96fec7c7fb2386e4b7 1 foo
"bar"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With