设为首页 加入收藏

TOP

Python Redis链接建立实现分析(一)
2015-02-02 14:43:11 来源: 作者: 【 】 浏览:40
Tags:Python Redis 链接 建立 实现 分析

今天在写zabbix storm job监控脚本的时候用到了python的redis模块,之前也有用过,但是没有过多的了解,今天看了下相关的api和源码,看到有ConnectionPool的实现,这里简单说下。
在ConnectionPool之前,如果需要连接redis,我都是用StrictRedis这个类,在源码中可以看到这个类的具体解释:


redis.StrictRedis 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


使用的方法:


?r=redis.StrictRedis(host=xxxx, port=xxxx, db=xxxx)


?r.xxxx()


有了ConnectionPool这个类之后,可以使用如下方法


pool = redis.ConnectionPool(host=xxx, port=xxx, db=xxxx)


r = redis.Redis(connection_pool=pool)


这里Redis是StrictRedis的子类
简单分析如下:
在StrictRedis类的__init__方法中,可以初始化connection_pool这个参数,其对应的是一个ConnectionPool的对象:


class StrictRedis(object):


........


? ? def __init__(self, host='localhost', port=6379,


? ? ? ? ? ? ? ? db=0, password=None, socket_timeout=None,


? ? ? ? ? ? ? ? socket_connect_timeout=None,


? ? ? ? ? ? ? ? socket_keepalive=None, socket_keepalive_options=None,


? ? ? ? ? ? ? ? connection_pool=None, unix_socket_path=None,


? ? ? ? ? ? ? ? encoding='utf-8', encoding_errors='strict',


? ? ? ? ? ? ? ? charset=None, errors=None,


? ? ? ? ? ? ? ? decode_responses=False, retry_on_timeout=False,


? ? ? ? ? ? ? ? ssl=False, ssl_keyfile=None, ssl_certfile=None,


? ? ? ? ? ? ? ? ssl_cert_reqs=None, ssl_ca_certs=None):


? ? ? ? if not connection_pool:


? ? ? ? ? ? ..........


? ? ? ? ? ? ? connection_pool = ConnectionPool(**kwargs)


? ? ? ? self.connection_pool = connection_pool


在StrictRedis的实例执行具体的命令时会调用execute_command方法,这里可以看到具体实现是从连接池中获取一个具体的连接,然后执行命令,完成后释放连接:


? # COMMAND EXECUTION AND PROTOCOL PARSING


? ? def execute_command(self, *args, **options):


? ? ? ? "Execute a command and return a parsed response"


? ? ? ? pool = self.connection_pool


? ? ? ? command_name = args[0]


? ? ? ? connection = pool.get_connection(command_name, **options)? #调用ConnectionPool.get_connection方法获取一个连接


? ? ? ? try:


? ? ? ? ? ? connection.send_command(*args)? #命令执行,这里为Connection.send_command


? ? ? ? ? ? return self.parse_response(connection, command_name, **options)


? ? ? ? except (ConnectionError, TimeoutError) as e:


? ? ? ? ? ? connection.disconnect()


? ? ? ? ? ? if not connection.retry_on_timeout and isinstance(e, TimeoutError):


? ? ? ? ? ? ? ? raise


? ? ? ? ? ? connection.send_command(*args)?


? ? ? ? ? ? return self.parse_response(connection, command_name, **options)


? ? ? ? finally:


? ? ? ? ? ? pool.release(connection)? #调用ConnectionPool.release释放连接


在来看看ConnectionPool类:


? ? class ConnectionPool(object):?


? ? ? ...........


? ? def __init__(self, connection_class=Connection, max_connections=None,


? ? ? ? ? ? ? ? **connection_kwargs):? #类初始化时调用构造函数


? ? ? ? max_connections = max_connections or 2 ** 31


? ? ? ? if not isinstance(max_connections, (int, long)) or max_connections < 0:? #判断输入的max_connections是否合法


? ? ? ? ? ? raise ValueError('"max_connections" must be a positive integer')


? ? ? ? self.connection_class = connection_class? #设置对应的参数


? ? ? ? self.connection_kwargs = connection_kwargs


? ? ? ? self.max_connections = max_connections


? ? ? ? self.reset()? #初始化ConnectionPool 时的reset操作


? ? def reset(self):


? ? ? ? self.pid = os.getpid()


? ? ? ? self._created_connections = 0? #已经创建的连接的计数器


? ? ? ? self._available_connections = []? #声明一个空的数组,用来存放可用的连接


? ? ? ? self._in_use_connections = set()? #声明一个空的集合,用来存放已经在用的连接


? ? ? ? self._check_lock = threading.Lock()


.......


? ? def get_connection(self, command_name, *keys, **options):? #在连接池中获取连接的方法

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Python使用xinetd处理多客户端 下一篇Java中ListIterator和Iterator详..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: