INCRBY、DECRBY:对整数值执行加法操作和减法操作

当字符串键存储的值能够被 Redis 解释为整数时,用户就可以通过 INCRBY 命令和 DECRBY 命令对被存储的整数值执行加法或减法操作。

INCRBY 命令用于为整数值加上指定的整数增量,并返回键在执行加法操作之后的值:

INCRBY key increment

以下代码展示了如何使用 INCRBY 命令去增加一个字符串键的值:

redis> SET number 100
OK
redis> GET number
"100"
redis> INCRBY number 300 -- 将键的值加上300
(integer) 400
redis> INCRBY number 256 -- 将键的值加上256
(integer) 656
redis> INCRBY number 1000 -- 将键的值加上1000
(integer) 1656
redis> GET number
"1656"

与 INCRBY 命令的作用正好相反,DECRBY 命令用于为整数值减去指定的整数减量,并返回键在执行减法操作之后的值:

DECRBY key increment

以下代码展示了如何使用 DECRBY 命令去减少一个字符串键的值:

redis> SET number 10086
OK
redis> GET number
"10086"
redis> DECRBY number 300 -- 将键的值减去300
(integer) 9786
redis> DECRBY number 786 -- 将键的值减去786
(integer) 9000
redis> DECRBY number 5500 -- 将键的值减去5500
(integer) 3500
redis> GET number
"3500"

类型限制

当字符串键的值不能被 Redis 解释为整数时,对键执行 INCRBY 命令或是 DECRBY 命令将返回一个错误:

redis> SET pi 3.14
OK
redis> INCRBY pi 100 -- 不能对浮点数值执行
(error) ERR value is not an integer or out of range
redis> SET message "hello world"
OK
redis> INCRBY message -- 不能对字符串值执行
(error) ERR wrong number of arguments for 'incrby' command
redis> SET big-number 123456789123456789123456789
OK
redis> INCRBY big-number 100 -- 不能对超过64位长度的整数执行
(error) ERR value is not an integer or out of range

另外需要注意的一点是,INCRBY 和 DECRBY 的增量和减量也必须能够被 Redis 解释为整数,使用其他类型的值作为增量或减量将返回一个错误:

redis> INCRBY number 3.14 -- 不能使用浮点数作为增量
(error) ERR value is not an integer or out of range
redis> INCRBY number "hello world" -- 不能使用字符串值作为增量
(error) ERR value is not an integer or out of range

处理不存在的键

当 INCRBY 命令或 DECRBY 命令遇到不存在的键时,命令会先将键的值初始化为 0,然后再执行相应的加法操作或减法操作。

以下代码展示了 INCRBY 命令是如何处理不存在的键 x 的:

redis> GET x -- 键x不存在
(nil)
redis> INCRBY x 123 -- 先将键x的值初始化为0,然后再执行加上123的操作
(integer) 123
redis> GET x
"123"

以下代码展示了 DECRBY 命令是如何处理不存在的键 y 的:

redis> GET y -- 键y不存在
(nil)
redis> DECRBY y 256 -- 先将键y的值初始化为0,再执行减去256的操作
(integer) -256
redis> GET y
"-256"

其它信息

  • 复杂度:O(1)。

  • 版本要求:INCRBY 命令和 DECRBY 命令从 Redis 1.0.0 开始可用。