python DBUtils.PooledDB 中 maxcached 和 maxconnections

PooledDB 有这么几个参数

  • mincached : the initial number of idle connections in the pool (the default of 0 means no connections are made at startup)

  • maxcached: the maximum number of idle connections in the pool (the default value of 0 or None means unlimited pool size)

  • maxconnections: maximum number of connections generally allowed (the default value of 0 or None means any number of connections)

  • blocking: determines behavior when exceeding the maximum

其中 maxconnections 的描述有点奇怪,它说 generally allowed,为什么是 generally ?

设定 blocking=True,使用 MySQLdb 试验的结果如下:

1. 如果 maxconnections 参数不存在,那么连接数可以无限大,直至打满 mysql

2. 如果 maxcached < maxconnections,那么最大连接数就是 maxconnections, 但是奇怪的是,并不是所有 connections 都被复用了,pool 还是会创建新的连接

3. 如果 maxcached > maxconnections,那么最大连接数就是 maxcached, 同样存在 connections 可以复用但是还是会创建新连接的问题

测试代码

from threading import Thread
from DBUtils.PooledDB import PooledDB
from datetime import datetime
import MySQLdb

pool = PooledDB(creator=MySQLdb,
                         mincached=1,
                         maxcached=3,
                         maxconnections=3,
                         blocking=True,
                         user="test",
                         passwd="test",
                         db="test")

def test1(pool):
    print("start: %s" % datetime.now())
    conn = pool.connection()
    print conn
    cursor = conn.cursor()
    print("select: %s" % datetime.now())
    cursor.execute("select sleep(10)")
    cursor.close()
    conn.close()
    print("end: %s" % datetime.now())

def main():
    for i in xrange(15):
        Thread(target=test1, args=(pool,)).start()

if __name__ == "__main__":
    main()
原文地址:https://www.cnblogs.com/senjougahara/p/5698348.html