INCRBY
命令用于为整数值加上指定的整数增量,并返回键在执行加法操作之后的值:
以下代码展示了如何使用 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
- redis> GET number
- "1656"
以下代码展示了如何使用 命令去减少一个字符串键的值:
- 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
- redis> GET number
- "3500"
当字符串键的值不能被 Redis 解释为整数时,对键执行 INCRBY
命令或是 DECRBY
命令将返回一个错误:
- 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
命令或 命令遇到不存在的键时,命令会先将键的值初始化为 0
,然后再执行相应的加法操作或减法操作。
以下代码展示了 INCRBY
命令是如何处理不存在的键 x
的:
- redis> GET y -- 键 y 不存在
- (nil)
- redis> DECRBY y 256 -- 先将键 y 的值初始化为 0 ,然后再执行减去 256 的操作
- (integer) -256
- redis> GET y
- "-256"