首页 > 解决方案 > 实现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这样它就不会出错。

有没有办法做到这一点?

标签: redislua

解决方案


将您的第一次增量尝试包装在一个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 )

推荐阅读