redis - 实现redis脚本错误回滚
问题描述
如果 redis lua 脚本中途失败,有没有办法回滚更改?
即,通过 EVAL 调用它,当前代码将向键添加一个然后抛出
local function inc2 (key)
redis.call('INCRBY',key,1)
error("FAIL")
redis.call('INCRBY',key,1)
end
return inc2(KEYS[1])
我希望能够有一种回滚第一个的方法,INCRBY
这样它就不会出错。
有没有办法做到这一点?
解决方案
将您的第一次增量尝试包装在一个pcall()
local function inc2( key )
local success, msg = pcall( redis.call( 'INCR', key ) )
if success then
redis.call( 'INCR', key )
else
error( msg )
redis.call( 'DECR', key )
end
end
inc2( KEYS[1] )
在我看来,检查值是否在开始范围内会更有效。
local function inc2( key, max )
if redis.call( 'get', key ) < max then
redis.call( 'INCRBY', key, 2 )
end
end
inc2( KEYS[1], 20 )
推荐阅读
- javascript - 导入引导 js 文件时出现意外令牌错误
- json-ld - JSON-LD:将自定义 URI 分配给上下文中的空白节点
- android - 从 URL 加载的 Jetpack Compose 图像始终为黑色
- c++ - PlatformIO collect2.exe 链接器错误:未定义引用
- magento - 如果在 magento 2 中应用购物车价格规则后如何跳过所有适用规则
- ios - 如何在 SwiftUI 中从 URLSession 获取响应
- html - WebUSB 打印 HTML 格式的内容
- android - 如何在 Android 应用程序中调试由 UnixDirectoryStream 引起的泄漏
- python - Python中的意外名称错误
- drupal - Drupal 控制台错误