Redis如何使EVAL脚本表现得像MULTI/EXEC? [英] Redis how to make EVAL script behave like MULTI / EXEC?

查看:62
本文介绍了Redis如何使EVAL脚本表现得像MULTI/EXEC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Lua脚本时,我注意到的一件事是,在包含多个操作的脚本中,如果在脚本执行过程中抛出了错误,则在错误之前完成的操作实际上会反映在数据库中.这与MULTI/EXEC相反,在MULTI/EXEC中,所有操作都成功或失败.

One thing I noticed when playing around with Lua scripts is that, in a script containing multiple operations, if an error is thrown halfway through the execution of the script, the operations that completed before the error will actually be reflected in the database. This is in contrast to MULTI / EXEC, where either all operations succeed or fail.

例如,如果我有如下脚本:

For example, if I have a script like the following:

redis.call("hset", "mykey", "myfield", "val")
local expiry = someFunctionThatMightThrow()
redis.call("expire", "mykey", expiry)

我对此进行了测试,第一个 hset 调用的结果反映在 redis 中.有什么办法可以让 lua 脚本表现得如此,如果在脚本执行期间抛出任何错误,那么在该脚本执行期间执行的所有操作都将被恢复?

I tested this and the results of the first hset call were reflected in redis. Is there any way to make the lua script behave so that if any error is thrown during the script, then all actions performed during that script execution are reverted?

推荐答案

上面针对我的注释的示例脚本,关于错误手动回滚.注意:语法未经验证.

Sample script for my comment above, on error manually rollback. Note: Syntax is not verified.

redis.call("hset", "mykey", "myfield", "val")
local expiry,error = pcall(someFunctionThatMightThrow())
if expiry ~= nil then
  redis.call("expire", "mykey", expiry)
else
  redis.call("hdel", "mykey", "myfield")
end

这篇关于Redis如何使EVAL脚本表现得像MULTI/EXEC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆