实现 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,以便在出错时什么都不做。

有没有办法做到这一点?

点赞
用户3342050
用户3342050

将你的第一次尝试增加功能包裹在 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 )
2020-11-11 18:33:20