v1# -*- coding: utf-8 -*-# __author__ = 'zhourudong'# 连接池的实现import pymysqlimport Queuefrom pymysql.cursors import DictCursorclass ConnectionPool: def __init__(self, **kwargs): self.size = kwargs.pop('size', 10) # 允许最大的连接 self.idle = kwargs.pop('idle', 3) # 空闲连接 self.kwargs = kwargs self.length = 0 # 已用连接 self.connections = Queue.Queue(maxsize=self.idle) def _connect(self): # 创建连接的函数 if not self.connections.full(): # 如果当前连接小于预留的连接则创建 conn = pymysql.connect(**self.kwargs) self.connections.put(conn) # 放到池中 self.length += 1 else: raise RuntimeError('lot of connections ') def _close(self, conn): conn.close() # self.length -= 1 # 17分钟 def get(self, timeout=None): if self.connections.empty() and self.length < self.size: # 如果连接池为空 或者已用连接小于设置连接数上限 self._connect() return self.connections.get(timeout=timeout) def return_resource(self, conn): if self.connections.full(): # 如果连接池中剩余的连接大于 设置连接上线)(连接池满则关闭, 否则把连接放到连接池中) self._close(conn) return self.connections.put(conn)if __name__ == '__main__': pool = ConnectionPool(host='127.0.0.1', port=23316, user='root', password='123456', database='zrd', cursorclass=DictCursor) for _ in range(11): conn = pool.get() conn.cursor() # conn = pool.get() # try: # # with conn as cur: # cur.execute(""" SELECT * FROM `user`""") # for res in cur.fetchall(): # print res # finally: # pool.return_resource(conn)
阅读全文…