Redis INCRBY命令

Redis INCRBY命令教程

Redis INCRBY 命令用于将 RedisKEY 所储存的值增加 increment 。该操作支持的最大值为 64 位(bit)有符号数。

如果 KEY 不存在,那么 KEY 的值会先被初始化为 0 ,然后再执行 INCRBY 操作。如果值包含错误的类型,或字符串类型的值不能表示为数字,那么返回一个错误。

Redis INCRBY命令详解

语法

192.168.98.70:6379> INCRBY KEY increment

参数

参数 作用
KEY 需要增加值的 KEY
increment 具体增加的值。

返回值

增加 increment 之后, KEY 的值。

时间复杂度

O(1)

可用版本

>= 1.0.0

案例

KEY不存在

当 KEY 不存在时,会被作为 0 处理

# KEY 不存在 192.168.98.70:6379> EXISTS haicoder.net (integer) 0 192.168.98.70:6379> INCRBY haicoder.net 3 (integer) 3 192.168.98.70:6379> GET haicoder.net "3" 192.168.98.70:6379> DEL haicoder.net (integer) 1

我们首先,使用 EXISTS 命令,判断 haicoder.net 不存在。接着,使用 INCRBY 命令,将不存在的 haicoder.net 的值加 3 。

最后,使用 GET 命令,获取 haicoder.net 的值为 3,说明不存在的 KEY 被 INCRBY 操作时当做了 0 处理 。

KEY存在

当 KEY 存在时,会将相应的值减 increment

# KEY 存在 192.168.98.70:6379> SET haicoder.net 100 OK 192.168.98.70:6379> INCRBY haicoder.net 3 (integer) 103 192.168.98.70:6379> INCRBY haicoder.net 2 (integer) 105 192.168.98.70:6379> INCRBY haicoder.net 5 (integer) 110 192.168.98.70:6379> DEL haicoder.net (integer) 1

我们首先,使用 SET 命令,设置 haicoder.net 的值为 100。接着,使用 INCRBY 命令,将 haicoder.net 的值加 3 ,此时值变成了 103。

接着,再次使用 INCRBY 命令,将 haicoder.net 的值加 2 ,此时值变成了 105。最后,再次使用 INCRBY 命令,将 haicoder.net 的值加 5 ,此时值变成了 110。

KEY为非数值型

当 KEY 为非数值型,会报错

# 非数值型 192.168.98.70:6379> SET haicoder.net Redis OK 192.168.98.70:6379> INCRBY haicoder.net 1 (error) ERR value is not an integer or out of range 192.168.98.70:6379> DEL haicoder.net (integer) 1

我们首先,使用 SET 命令,设置 haicoder.net 的值为 Redis。最后,使用 INCRBY 命令,将 haicoder.net 的值加 1 ,此时直接报错。

Redis INCRBY命令总结

Redis INCRBY 命令用于将 Redis 中 KEY 所储存的值增加 increment 。Redis INCRBY 命令语法:

192.168.98.70:6379> INCRBY KEY increment