redis系列: redis-py 源码分析 - 一次完整的请求

本文深入分析了redis-py的源码,从实例化、发送命令到获取响应,详细解释了每个阶段的实现。在实例化过程中,创建了连接池,发送命令时涉及获取连接、发送命令、解析响应和释放连接等步骤。整个过程展示了redis-py如何高效地与Redis服务器交互。

本文主要分析 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值