首页 > 编程笔记

Redis HINCRBY命令的用法

Redis HINCRBY 命令的基本语法如下。
HINCRBY key field increment
HINCRBY 用于将散列表 key 中的 field 的值加上增量 increment。增量 increment 可以是负数,即对 field 进行减法操作。

返回值:执行 HINCRBY 命令之后,散列表 key 中 field 的值。

【实例 1】给指定的 field 加上正数。
127.0.0.1:6379> HEXISTS page counter
(integer) 0
127.0.0.1:6379> HINCRBY page counter 20
(integer) 20
127.0.0.1:6379> HGET page counter
"20"

【实例 2】给指定的 field 加上负数。
127.0.0.1:6379> HGET counter page_view
"200"

127.0.0.1:6379> HINCRBY counter page_view -50
(integer) 150

127.0.0.1:6379> HGET counter page_view
"150"

【实例 3】尝试对字符串值的 field 执行 HINCRBY 命令。
127.0.0.1:6379> HSET user name "xinping"       # 对field设定一个字符串值
(integer) 1
127.0.0.1:6379> HGET user name
"xinping"
127.0.0.1:6379> HINCRBY user name 1            # 命令执行失败,错误
(error) ERR hash value is not an integer
127.0.0.1:6379> HGET user name                 # 原值不变
"xinping"

推荐阅读