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

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

    1. redis> SET number 100
    2. OK
    3.  
    4. redis> GET number
    5. "100"
    6.  
    7. redis> INCRBY number 300 -- 将键的值加上 300
    8. (integer) 400
    9.  
    10. redis> INCRBY number 256 -- 将键的值加上 256
    11. (integer) 656
    12.  
    13. redis> INCRBY number 1000 -- 将键的值加上 1000
    14.  
    15. redis> GET number
    16. "1656"

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

    1. redis> SET number 10086
    2. OK
    3.  
    4. redis> GET number
    5. "10086"
    6.  
    7. redis> DECRBY number 300 -- 将键的值减去 300
    8. (integer) 9786
    9.  
    10. redis> DECRBY number 786 -- 将键的值减去 786
    11. (integer) 9000
    12.  
    13. redis> DECRBY number 5500 -- 将键的值减去 5500
    14.  
    15. redis> GET number
    16. "3500"

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

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

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

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

    1. redis> GET y -- y 不存在
    2. (nil)
    3.  
    4. redis> DECRBY y 256 -- 先将键 y 的值初始化为 0 ,然后再执行减去 256 的操作
    5. (integer) -256
    6.  
    7. redis> GET y
    8. "-256"