python的urllib3库(http连接池)

Python013

python的urllib3库(http连接池),第1张

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,则不会阻塞线程,但是会新开一个链接.有一个弊端是,使用完之后这个链接会关闭,所以如果 多线程经常建立链接会影响性能,多占用多余的资源

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)

不用连接池的MySQL连接方法

import MySQLdb

conn= MySQLdb.connect(host='localhost',user='root',passwd='pwd',db='myDB',port=3306)

cur=conn.cursor()

SQL="select * from table1"

r=cur.execute(SQL)

r=cur.fetchall()

cur.close()

conn.close()

用连接池后的连接方法

import MySQLdb

from DBUtils.PooledDB import PooledDB

pool = PooledDB(MySQLdb,5,host='localhost',user='root',passwd='pwd',db='myDB',port=3306) #5为连接池里的最少连接数