之前详细介绍了 Redis命令 - Hashes命令组常用命令,同样的命令,本文将用python调用redis库封装好的方法。
1、HSET key field value
2、HMSET key field value [field value…]
3、HSETNX key field value
4、HGET key field
5、HMGET key field [field …]
6、HGETALL key
7、HKEYS key
8、HVALS key
9、HEXISTS key field
10、HLEN key
11、HSTRLEN key field
12、HINCRBY key field increment
13、HINCRBYFLOAT key field increment
14、HDEL key field [field…]
import redis
from config.VAR import INT_REDIS_HOST, INT_REDIS_PORT, INT_REDIS_PASSWORD
# 便于修改,将redis的连接配置在VAR.py中,管理这些常量
r = redis.StrictRedis(host=INT_REDIS_HOST, port=INT_REDIS_PORT, password=INT_REDIS_PA
# HSET key field value
# HMSET key field value [field value…]
# HMSET在python中已经弃用了,不管一次设置多个字段还是一个字段都用HSET来实现
# 第1种方式:定义一个字典:包含所有将要设置的字段名称和字段值。
dict = {'username': 'zhangsan', 'password': '123456'}
print(r.hset("mytest", mapping=dict)) # 2,返回的是hash里键值对的个数
# 第2中方式:一次set一个字段和值。若key不存在,则创建key。若字段不存在,返回1;若字段已存在,返回0
r.hset("mytest", "username", "zhangsan") # 若打印返回值,返回的是:0
r.hset("mytest", "age", "18") # 1
r.hset("mytest", "address", "china") # 1
# HSETNX key field value
print(r.hsetnx("mytest", "username", "zhangsan")) # 0,此字段已存在
print(r.hsetnx("mytest", "phone", "13811111111")) # 1,此字段不存在,设置成功
# HGET key field
print(r.hget("mytest", "username")) # b'zhangsan'
# HMGET key field [field …]
print(r.hmget("mytest", ["username", "age"])) # [b'zhangsan', b'18']
# HGETALL key
print(r.hgetall(
"mytest")) # {b'password': b'123456', b'username': b'zhangsan', b'age': b'18', b'address': b'china', b'phone': b'13811111111'}
# HLEN key
print(r.hlen("mytest")) # 5
# HSTRLEN key field
print(r.hstrlen("mytest", "username")) # 8,字段值的长度
# HKEYS key
print(r.hkeys("mytest")) # [b'password', b'username', b'age', b'address', b'phone']
# HVALS key
print(r.hvals("mytest")) # [b'123456', b'zhangsan', b'18', b'china', b'13811111111']
# HEXISTS key field
print(r.hexists("mytest", "username")) # True
print(r.hexists("mytest", "username1")) # False
# HINCRBY key field increment
print(r.hincrby("mytest", "age")) # amount默认是1,执行命令后,返回值是19
print(r.hincrby("mytest", "age", 9)) # 28
# print(r.hincrby("mytest", "username", 1)) # 如果该字段值不是纯数字就会报错
# HINCRBYFLOAT key field increment
print(r.hincrbyfloat("mytest", "age", 2.0)) # 30.0
print(r.hincrbyfloat("mytest", "age", -3.0)) # 27.0
# print(r.hincrbyfloat("mytest", "username", 1.0)) # 如果该字段值不是纯数字就会报错
# HDEL key field [field…]
# 删除某个字段
print(r.hdel("mytest", *["address"])) # 1, 返回的是删除掉的键值对的长度
print(r.hdel("mytest", *["age", "phone"])) # 2
# 删除所有字段
print(r.hdel("mytest", *list(r.hkeys("mytest")))) # 2
print(r.hgetall("mytest")) # {}