发牌SO 发表于 2018-8-3 11:49:56

python redis链接建立实现分析

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):#在连接池中获取连接的方法
  
      "Get a connection from the pool"
  
      self._checkpid()
  
      try:
  
            connection = self._available_connections.pop()#获取并删除代表连接的元素,在第一次获取connectiong时,因为_available_connections是一个空的数组,
  
            会直接调用make_connection方法
  
      except IndexError:
  
            connection = self.make_connection()
  
      self._in_use_connections.add(connection)   #向代表正在使用的连接的集合中添加元素
  
      return connection
  
    def make_connection(self): #在_available_connections数组为空时获取连接调用的方法
  
      "Create a new connection"
  
      if self._created_connections >= self.max_connections:   #判断创建的连接是否已经达到最大限制,max_connections可以通过参数初始化
  
            raise ConnectionError("Too many connections")
  
      self._created_connections += 1   #把代表已经创建的连接的数值+1
  
      return self.connection_class(**self.connection_kwargs)   #返回有效的连接,默认为Connection(**self.connection_kwargs)
  
    def release(self, connection):#释放连接,链接并没有断开,只是存在链接池中
  
      "Releases the connection back to the pool"
  
      self._checkpid()
  
      if connection.pid != self.pid:
  
            return
  
      self._in_use_connections.remove(connection)   #从集合中删除元素
  
      self._available_connections.append(connection) #并添加到_available_connections 的数组中
  
    def disconnect(self): #断开所有连接池中的链接
  
      "Disconnects all connections in the pool"
  
      all_conns = chain(self._available_connections,
  
                        self._in_use_connections)
  
      for connection in all_conns:
  
            connection.disconnect()
页: [1]
查看完整版本: python redis链接建立实现分析