Skip to content

Instantly share code, notes, and snippets.

@mattjanssen
Last active November 12, 2020 18:18
Show Gist options
  • Save mattjanssen/3080b321dbfc101248c1bdee3c4d79c1 to your computer and use it in GitHub Desktop.
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.
<?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