Last active
November 12, 2020 18:18
-
-
Save mattjanssen/3080b321dbfc101248c1bdee3c4d79c1 to your computer and use it in GitHub Desktop.
Use Predis EVAL with a Redis Lua script to decrement a key, delete the key if the new value is zero, and then return the new value atomically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$lua = <<<LUA | |
local c = redis.call('DECR', KEYS[1]) | |
if c == 0 then | |
redis.call('DEL', KEYS[1]) | |
end | |
return c | |
LUA; | |
// Argument 1 is the Lua script. | |
// Argument 2 is the number of keys being passed to the script (always 1 for this script). | |
// Argument 3 is the key to decrement/delete. | |
$count = $predisClient->eval($lua, 1, 'foo-bar-key'); | |
// An alternative would be to use a WATCH + MULTI + EXEC transaction, but the Redis community seems to prefer Lua. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment