Redis:如何保证只 incr 存在的key ?


#Redis#


使用 incr 指令时,若 key 不存在,则会初始化该 key,并将 value 置为 1 。

如何保证只 incr 存在的key ? 答案是用 lua 脚本。

脚本:

local exists = redis.call('exists', KEYS[1]); 
if (exists == 1) then 
    return redis.call('incr', KEYS[1]); 
end 
return nil;

测试示例1:

127.0.0.1:6379> set test_key 10
OK
127.0.0.1:6379> eval "local exists = redis.call('exists', KEYS[1]); if (exists == 1) then return redis.call('incr', KEYS[1]); end return nil;" 1 test_key
(integer) 11

脚本返回了 11 ,说明 incr 生效了。

测试示例2:

127.0.0.1:6379> eval "local exists = redis.call('exists', KEYS[1]); if (exists == 1) then return redis.call('incr', KEYS[1]); end return nil;" 1 test_key_not_exists
(nil)

脚本返回了 nil,说明未进行 incr 操作。


( 本文完 )