Django数据库连接池(mysql)
都知道django每次请求都会连接数据库和释放数据库连接。Django为每个请求使⽤新的数据库连接。⼀开始这个⽅法⾏得通。然⽽随着服务器上的负载的增加,创建/销毁连接数据库开始花⼤量的时间。要避免这个,你可以使⽤数据库连接池。
tuba本⽂使⽤ DBUtils的连接池, 使Django持久化数据库连接。
DBUtils实现django连接池
DBUtils 是⼀套⽤于管理数据库连接池的Python包,为⾼频度⾼并发的数据库访问提供更好的性能,可以⾃动管理连接对象的创建和释放。并允许对⾮线程安全的数据库接⼝进⾏线程安全包装。sidekick
django结合DBUtils使⽤,数据库连接管理完全交给DBUtils处理,平滑切换db backends。
django使⽤连接的过程:
请求开始: 新建连接(从DBUtils管理的连接池中获取连接)
请求结束: 关闭连接(实际由DBUtils将连接返还连接池)
DBUtils
DBUtils提供两种外部接⼝:
PersistentDB :提供线程专⽤的数据库连接,并⾃动管理连接。tear gas
PooledDB :提供线程间可共享的数据库连接,并⾃动管理连接。
实测证明 PersistentDB 的速度是最⾼的,但是在某些特殊情况下,数据库的连接过程可能异常缓慢,⽽此时的PooledDB则可以提供相对来说平均连接时间⽐较短的管理⽅式。
django ttings日语口语
DATABASES = {
"default": {
"ENGINE": "db_pool.sql",
"NAME": "xxx",
"USER": "xxx",
ytt"PASSWORD": "xxx",
"HOST": "mysql",
"PORT": "3306",
"ATOMIC_REQUESTS": True,
"CHARSET": "utf8",
大专生留学
"COLLATION": "utf8_bin",
"POOL": {
"mincached": 5,
"maxcached ": 500,
}相形见绌
}
}
其中连接池(POOL)配置参见 DBUtils的 PooledDB参数:
mincached: initial number of idle connections in the pool
puju
(0 means no connections are made at startup)
maxcached: maximum number of idle connections in the pool
propod
(0 or None means unlimited pool size)
maxshared: maximum number of shared connections
(0 or None means all connections are dedicated)
When this maximum number is reached, connections are
shared if they have been requested as shareable. maxconnections: maximum number of connections generally allowed (0 or None means an arbitrary number of connections) blocking: determines behavior when exceeding the maximum
(if this is t to true, block and wait until the number of
connections decreas, otherwi an error will be reported) maxusage: maximum number of reus of a single connection
(0 or None means unlimited reu)
When this maximum usage number of the connection is reached, the connection is automatically ret (clod and reopened). tssion: optional list of SQL commands that may rve to prepare the ssion, e.g. ["t datestyle to ...", "t time zone ..."]
ret: how connections should be ret when returned to the pool
(Fal or None to rollback transcations started with begin(),
True to always issue a rollback for safety's sake)
failures: an optional exception class or a tuple of exception class for which the connection failover mechanism shall be applied,
if the default (OperationalError, InternalError) is not adequate ping: determines when the connection should be checked with ping() (0 = None = never, 1 = default = whenever fetched from the pool, 2 = when a cursor is created, 4 = when a query is executed,
7 = always, and all other bit combinations of the values)英语专四