python怎么使用mysql数据库连接池

python怎么使用mysql数据库连接池,第1张

import MySQLdb

import time

import string

import redis

class PooledConnection:

#构建连接池实例

def __init__(self, maxconnections, connstr,dbtype):

from Queue import Queue

self._pool = Queue(maxconnections) # create the queue

self.connstr = connstr

self.dbtype=dbtype

self.maxconnections=maxconnections

#根据你给数目来创建链接,并且写入刚才创建的队列里面。

try:

for i in range(maxconnections):

self.fillConnection(self.CreateConnection(connstr,dbtype))

except Exception,e:

raise e

def fillConnection(self,conn):

try:

self._pool.put(conn)

except Exception,e:

raise "fillConnection error:"+str(e)

def returnConnection(self, conn):

try:

self._pool.put(conn)

except Exception,e:

raise "returnConnection error:"+str(e)

def getConnection(self):

try:

return self._pool.get()

except Exception,e:

raise "getConnection error:"+str(e)

def ColseConnection(self,conn):

try:

self._pool.get().close()

self.fillConnection(self.CreateConnection(connstr,dbtype))

except Exception,e:

raise "CloseConnection error:"+str(e)

urllib3.disable_warnings() # 禁用各种urllib3的警告

1.retry:重试重定向次数,默认次数为3次,如果想要关闭重定向,但是不想关闭重试只需redirect=Flase,如果重定向重试都关闭,retries=False

2.timeout:超时,可以设置链接超时和读超时

timeout = urllib3.Timeout(connect=1,read=2)

3.numpools:池子的数量,假如有10个池子,当你访问第11个ip的时候第一个池子会被干掉,然后建一个

新的供第11个使用.一个池子是作用于同一个ip下的,即 http://aaa.com/a 和 http://aaa.com/b 是会共用一个池子的

4.maxsize:一个池子缓存的最大连接数量.没有超过最大链接数量的链接都会被保存下来.在block为false的情况下,

添加的额外的链接不会被保存一般多用于多线程之下,一般情况是设置为和线程数相等的数量, 保证每个线程都能访问一个链接.

5.还有一个参数 是 block ,默认为False,如果线程数量大于池子最大链接数量.这时设置block为true,则会阻塞线程,因为线程会等其他线程使用完链接,如果设置为False,则不会阻塞线程,但是会新开一个链接.有一个弊端是,使用完之后这个链接会关闭,所以如果 多线程经常建立链接会影响性能,多占用多余的资源


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/9835598.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-02
下一篇 2023-05-02

发表评论

登录后才能评论

评论列表(0条)

保存