文章目录
本文主要分析 redis-py
源码,阐述 redis-py
连接过程和如何获取响应
先来看一下 redis-py 的项目结构,结构比较简单,也很清晰。
.
├── __init__.py
├── _compat.py python2.x向后兼容的内部模块
├── client.py 实现redis客户端
├── connection.py 实现连接池类,连接类和解析类
├── exceptions.py 异常模块
├── lock.py 实现共享、分布式锁
├── sentinel.py redis高可用客户端
└── utils.py 一些其他模块
我们从一个完整的请求开始阅读源码
In [1]: import redis
In [2]: r = redis.Redis(host='localhost', port=6379, db=1)
In [3]: r.ping()
Out[3]: True
根据示例代码,将分三个阶段解读源码:实例化、发送命令、获取响应
1. 实例化
1.1 代码实现
实例化的过程就是创建一个客户端的过程,使用起来比较方便,只需要实例化 Redis
类即可
In [1]: import redis
In [2]: r = redis.Redis(host='localhost', port=6379, db=0)
1.2 初始化源码
那么 Redis
类的初始化都做了什么呢?看下面的源码:
class Redis(object):
"""
Implementation of the Redis protocol.
This abstract class provides a Python interface to all Redis commands
and an implementation of the Redis protocol.
Connection and Pipeline derive from this, implementing how
the commands are sent and received to the Redis server
"""
def __init__(self, host='localhost', port=6379, db=0, connection_pool=None, max_connections=None):
if not connection_pool:
kwargs = {
'db': db,
'host': host,
'port': port,
'max_connections': max_connextions,
...
}
connection_pool = ConnectionPool(**kwargs)
self.connection_pool = connection_pool
上面的代码我省略了一些本次分析不需要的代码,目的是让我们的分析过程更明确。
我们在实例化 Redis
类时只传入了 redis-server
的地址参数,未指定连接池类,所以初始化的过程中实际上会先创建一个连接池。显然,我们不能忽略连接池的创建细节。
1.3 创建连接池
class ConnectionPool(ojbect):
"Generic connection pool"
def __init__(self, conn