redis的哈希使用的规则举个例子
时间: 2023-12-06 13:45:26 浏览: 108
Redis中的哈希使用类似于Python中的字典,它可以在一个键下存储多个键值对。下面是一个使用Redis哈希的例子:
```
# 连接Redis服务器
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 在哈希表'my_hash'中设置键值对
r.hset('my_hash', 'name', 'Alice')
r.hset('my_hash', 'age', 25)
r.hset('my_hash', 'gender', 'female')
# 获取哈希表'my_hash'中的值
print(r.hget('my_hash', 'name')) # 输出: b'Alice'
print(r.hgetall('my_hash')) # 输出: {b'name': b'Alice', b'age': b'25', b'gender': b'female'}
```
在上面的例子中,我们通过调用`hset()`方法在哈希表`my_hash`中设置了三个键值对,分别是`name`、`age`和`gender`。然后,我们通过调用`hget()`方法获取了键`name`对应的值,以及调用`hgetall()`方法获取了整个哈希表的键值对。注意,Redis中的哈希表键和值都是二进制数据,需要使用`b''`来表示。
阅读全文
相关推荐

















