文章目录
本文主要分析 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 an