一、安装 redis-py
首先,确保已经安装并启动了一台 Redis 服务。请参阅官方文档完成 Redis 服务器的安装与启动。
在项目环境中执行:
bash
pip install redis
Tip :如果希望获得更快的响应解析性能,可以额外安装
hiredis
:
bashpip install redis[hiredis]
如果系统中存在
hiredis>=1.0
,redis-py 会自动使用它进行底层二进制协议解析,无需修改代码。
注意:Python 3.12 以后的标准库移除了 distutils,旧版本的 redis-py 可能会安装失败,建议使用最新稳定版 redis-py。
二、连接到 Redis 并测试
在代码中导入并创建客户端实例:
python
import redis
# 默认连接到 localhost:6379,decode_responses=True 可直接返回字符串
r = redis.Redis(host='localhost', port=6379, decode_responses=True)
host
与port
:Redis 服务地址与端口;decode_responses=True
:将返回的 bytes 自动解码为 str。
示例:字符串读写
python
# 写入
r.set('foo', 'bar') # 返回 True
# 读取
value = r.get('foo') # 返回 'bar'
示例:Hash(字典)读写
python
# 批量写入 Hash
r.hset('user:123', mapping={
'name': 'Alice',
'email': '[email protected]',
'age': 30
})
# 读取整个 Hash
session = r.hgetall('user:123')
# 返回 {'name': 'Alice', 'email': '[email protected]', 'age': '30'}
三、核心特性速览
功能 | 方法示例 |
---|---|
字符串 | r.set() , r.get() |
列表 List | r.lpush() , r.rpop() |
集合 Set | r.sadd() , r.smembers() |
有序集合 ZSet | r.zadd() , r.zrange() |
哈希 Hash | r.hset() , r.hgetall() |
管道 Pipeline | pipe = r.pipeline(); pipe.set(...); pipe.execute() |
事务 Transaction | with r.pipeline() as pipe: pipe.multi(); ... |
发布/订阅 Pub/Sub | pub = r.pubsub(); pub.subscribe('chan') |
扫描迭代 SCAN | r.scan_iter() , r.hscan_iter() |
更多高级用法,请参考 redis-py 官方文档。
四、常见配置与调优
-
连接池
pythonpool = redis.ConnectionPool(host='localhost', port=6379, db=0) r = redis.Redis(connection_pool=pool)
复用 TCP 连接、提升并发性能。
-
超时与重试
pythonr = redis.Redis(socket_timeout=5, socket_connect_timeout=5, retry_on_timeout=True)
防止网络抖动导致阻塞。
-
SSL/TLS 连接
pythonr = redis.Redis( host='redis.example.com', port=6380, ssl=True, ssl_certfile='client.crt', ssl_keyfile='client.key', ssl_ca_certs='ca.pem' )
在云环境或生产集群中启用加密传输。
五、深入学习资源
- 官方命令参考 :https://redis-py.readthedocs.io/en/stable/
- 示例仓库 :https://github.com/redis/redis-py/tree/master/examples
- RedisOM for Python:面向对象的 Redis 客户端(文档模型)
- Redis Modules:RedisJSON、RediSearch、RedisGraph 等高级功能
通过上述步骤,你已能够在 Python 应用中快速集成并高效使用 Redis。接下来,可进一步探索管道、事务、发布/订阅模式,以及 Redis Streams、Lua 脚本与集群模式等进阶特性,以满足更复杂的业务需求。祝你开发顺利!