redis-py:Redis 官方 Python 客户端
redis-py:Redis 官方 Python 客户端
Redis 官方维护的 Python 客户端库 redis-py,目前在 GitHub 上获得了 13,558 个 Star:

redis-py 提供了 Redis 键值存储的 Python 接口,支持 Redis 7.2、7.4、8.0、8.2、8.4、8.6 和 8.8 版本。
如果你的项目需要在 Python 中使用 Redis,这是最直接的选择。它由 Redis 官方团队开发和维护,API 覆盖了所有开箱即用的 Redis 命令。

安装
一条 pip 命令搞定:
pip install redis
如果需要更快的响应解析性能,可以安装带 hiredis 支持的版本,它提供编译级别的解析器,大多数场景下不需要改动任何代码:
pip install "redis[hiredis]"
基本用法
连接本地 Redis 并执行读写操作:
>>> import redis
>>> r = redis.Redis(host='localhost', port=6379, db=0)
>>> r.set('foo', 'bar')
True
>>> r.get('foo')
b'bar'
默认返回的是 bytes 类型。如果想要直接拿到字符串,设置 decode_responses=True。
RESP3 协议支持
redis-py 5.0 开始支持 RESP3 协议。从 8.0 版本起,客户端默认使用 RESP3 通信,同时保持对旧版 RESP2 应用的兼容。新项目建议关闭旧式响应兼容:
>>> r = redis.Redis(host='localhost', port=6379, db=0, legacy_responses=False)
连接池
redis-py 默认使用连接池管理连接。每个 Redis 实例自带独立的连接池,也可以手动创建:
>>> pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
>>> r = redis.Redis(connection_pool=pool)
同时支持异步连接、集群连接和异步集群连接。
Pipeline
Pipeline 可以批量发送 Redis 命令,减少网络往返次数:
>>> pipe = r.pipeline()
>>> pipe.set('foo', 5)
>>> pipe.set('bar', 18.5)
>>> pipe.set('blee', "hello world!")
>>> pipe.execute()
[True, True, True]
PubSub
通过 PubSub 类订阅频道并接收消息:
>>> p = r.pubsub()
>>> p.subscribe('my-first-channel', 'my-second-channel')
>>> p.get_message()
{'pattern': None, 'type': 'subscribe', 'channel': b'my-second-channel', 'data': 1}
注意 PUBLISH 命令只能从 Redis 客户端实例调用,不能从 PubSub 实例调用。
搜索与查询
redis-py 6.0.0 起,客户端默认使用 DIALECT 2 执行全文搜索命令(如 FT.SEARCH 和 FT.AGGREGATE)。如果需要指定其他方言版本,可以通过 .dialect() 方法切换:
>>> from redis.commands.search.field import TextField
>>> from redis.commands.search.query import Query
>>> r.ft().create_index((TextField("name"),))
>>> q = Query("@name: James").dialect(1)
>>> r.ft().search(q)
版本兼容
| 库版本 | 支持的 Redis 版本 |
|---|---|
| 3.5.3 | <= 6.2 |
| >= 4.5.0 | 5.0 到 7.0 |
| >= 5.0.0 | 5.0 到 7.4 |
| >= 6.0.0 | 7.2 到最新 |
需要留意的是,redis-py 5.0 是最后一个支持 Python 3.7 的版本,5.1 要求 Python 3.8+。6.1.0 是最后一个支持 Python 3.8 的版本,6.2.0 要求 Python 3.9+。
的是,redis-py 5.0 是最后一个支持 Python 3.7 的版本,5.1 要求 Python 3.8+。6.1.0 是最后一个支持 Python 3.8 的版本,6.2.0 要求 Python 3.9+。
更多推荐



所有评论(0)