Redis 可以在服务器端执行 Lua 脚本 — 以单个 atomic 操作的形式运行多个命令。脚本可以实现复杂的原子逻辑、减少网络往返,是在 Redis 中执行多步原子操作的推荐方式。
运行 Lua 脚本
# EVAL runs a Lua script; KEYS[] and ARGV[] pass keys and arguments
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey myvalue
# a script can run multiple commands and logic atomically
EVAL "
local current = redis.call('GET', KEYS[1])
if current == ARGV[1] then
return redis.call('DEL', KEYS[1]) -- delete only if value matches (atomic check-and-delete)
end
return 0
" 1 lock:resource mytoken
