杂项之pymysql连接池

本节内容

  1. 本文的诞生
  2. 连接池及单例模式
  3. 多线程提升
  4. 协程提升
  5. 后记

1.本文的诞生

由于前几天接触了pymysql,在测试数据过程中,使用普通的pymysql插入100W条数据,消耗时间很漫长,实测990s也就是16.5分钟左右才能插完,于是,脑海中诞生了一个想法,能不能造出一个连接池出来,提升数据呢?就像一根管道太小,那就多加几根管道看效果如何呢?于是。。。前前后后折腾了将近一天时间,就有了本文的诞生。。。

2.连接池及单例模式

先说单例模式吧,为什么要在这使用单例模式呢?使用单例模式能够节省资源。

其实单例模式没有什么神秘的,简单的单例模式实现其实就是在类里面定义一个变量,再定义一个类方法,这个类方法用来为调用者提供这个类的实例化对象。(ps:个人对单例模式的一点浅薄理解...)

那么连接池是怎么回事呢?原来使用pymysql创建一个conn对象的时候,就已经和mysql之间创建了一个tcp的长连接,只要不调用这个对象的close方法,这个长连接就不会断开,这样,我们创建了一组conn对象,并将这些conn对象放到队列里面去,这个队列现在就是一个连接池了。

现在,我们先用一个连接,往数据库中插入100W条数据,下面是源码:

 import pymysql
import time
start=time.time()
conn = pymysql.connect(host="192.168.10.103",port=3306,user="root",passwd="",db="sql_example",charset="utf8")
conn.autocommit(True) # 设置自动commit
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 设置返回的结果集用字典来表示,默认是元祖
data=(("男",i,"张小凡%s" %i) for i in range(1000000)) # 伪造数据,data是个生成器
cursor.executemany("insert into tb1(gender,class_id,sname) values(%s,%s,%s)",data) # 可以使用executemany执行多条sql
# conn.commit()
cursor.close()
conn.close()
print("totol time:",time.time()-start)

执行结果为:

totol time: 978.7649309635162

3.多线程提升

使用多线程,在启动时创建一组线程,每个线程去连接池里面获取一个连接,然后插入数据,这样将会大大提升执行sql的速度,下面是使用多线程实现的连接池源码:

 from gevent import monkey
monkey.patch_all() import threading import pymysql
from queue import Queue
import time class Exec_db: __v=None def __init__(self,host=None,port=None,user=None,passwd=None,db=None,charset=None,maxconn=5):
self.host,self.port,self.user,self.passwd,self.db,self.charset=host,port,user,passwd,db,charset
self.maxconn=maxconn
self.pool=Queue(maxconn)
for i in range(maxconn):
try:
conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)
conn.autocommit(True)
# self.cursor=self.conn.cursor(cursor=pymysql.cursors.DictCursor)
self.pool.put(conn)
except Exception as e:
raise IOError(e) @classmethod
def get_instance(cls,*args,**kwargs):
if cls.__v:
return cls.__v
else:
cls.__v=Exec_db(*args,**kwargs)
return cls.__v def exec_sql(self,sql,operation=None):
"""
执行无返回结果集的sql,主要有insert update delete
"""
try:
conn=self.pool.get()
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
response=cursor.execute(sql,operation) if operation else cursor.execute(sql)
except Exception as e:
print(e)
cursor.close()
self.pool.put(conn)
return None
else:
cursor.close()
self.pool.put(conn)
return response def exec_sql_feach(self,sql,operation=None):
"""
执行有返回结果集的sql,主要是select
"""
try:
conn=self.pool.get()
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
response=cursor.execute(sql,operation) if operation else cursor.execute(sql)
except Exception as e:
print(e)
cursor.close()
self.pool.put(conn)
return None,None
else:
data=cursor.fetchall()
cursor.close()
self.pool.put(conn)
return response,data def exec_sql_many(self,sql,operation=None):
"""
执行多个sql,主要是insert into 多条数据的时候
"""
try:
conn=self.pool.get()
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
response=cursor.executemany(sql,operation) if operation else cursor.executemany(sql)
except Exception as e:
print(e)
cursor.close()
self.pool.put(conn)
else:
cursor.close()
self.pool.put(conn)
return response def close_conn(self):
for i in range(self.maxconn):
self.pool.get().close() obj=Exec_db.get_instance(host="192.168.10.103",port=3306,user="root",passwd="",db="sql_example",charset="utf8",maxconn=10) def test_func(num):
data=(("男",i,"张小凡%s" %i) for i in range(num))
sql="insert into tb1(gender,class_id,sname) values(%s,%s,%s)"
print(obj.exec_sql_many(sql,data)) job_list=[]
for i in range(10):
t=threading.Thread(target=test_func,args=(100000,))
t.start()
job_list.append(t)
for j in job_list:
j.join()
obj.close_conn()
print("totol time:",time.time()-start)

显示代码

开启10个连接池插入100W数据的时间:

totol time: 242.81142950057983

开启50个连接池插入100W数据的时间:

totol time: 192.49499201774597

开启100个线程池插入100W数据的时间:

totol time: 191.73923873901367

4.协程提升

使用协程的话,在I/O阻塞时,将会切换到其他任务去执行,这样理论上来说消耗的资源应该会比多线程要少。下面是协程实现的连接池源代码:

 from gevent import monkey
monkey.patch_all()
import gevent import pymysql
from queue import Queue
import time class Exec_db: __v=None def __init__(self,host=None,port=None,user=None,passwd=None,db=None,charset=None,maxconn=5):
self.host,self.port,self.user,self.passwd,self.db,self.charset=host,port,user,passwd,db,charset
self.maxconn=maxconn
self.pool=Queue(maxconn)
for i in range(maxconn):
try:
conn=pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset=self.charset)
conn.autocommit(True)
# self.cursor=self.conn.cursor(cursor=pymysql.cursors.DictCursor)
self.pool.put(conn)
except Exception as e:
raise IOError(e) @classmethod
def get_instance(cls,*args,**kwargs):
if cls.__v:
return cls.__v
else:
cls.__v=Exec_db(*args,**kwargs)
return cls.__v def exec_sql(self,sql,operation=None):
"""
执行无返回结果集的sql,主要有insert update delete
"""
try:
conn=self.pool.get()
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
response=cursor.execute(sql,operation) if operation else cursor.execute(sql)
except Exception as e:
print(e)
cursor.close()
self.pool.put(conn)
return None
else:
cursor.close()
self.pool.put(conn)
return response def exec_sql_feach(self,sql,operation=None):
"""
执行有返回结果集的sql,主要是select
"""
try:
conn=self.pool.get()
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
response=cursor.execute(sql,operation) if operation else cursor.execute(sql)
except Exception as e:
print(e)
cursor.close()
self.pool.put(conn)
return None,None
else:
data=cursor.fetchall()
cursor.close()
self.pool.put(conn)
return response,data def exec_sql_many(self,sql,operation=None):
"""
执行多个sql,主要是insert into 多条数据的时候
"""
try:
conn=self.pool.get()
cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)
response=cursor.executemany(sql,operation) if operation else cursor.executemany(sql)
except Exception as e:
print(e)
cursor.close()
self.pool.put(conn)
else:
cursor.close()
self.pool.put(conn)
return response def close_conn(self):
for i in range(self.maxconn):
self.pool.get().close() obj=Exec_db.get_instance(host="192.168.10.103",port=3306,user="root",passwd="",db="sql_example",charset="utf8",maxconn=10) def test_func(num):
data=(("男",i,"张小凡%s" %i) for i in range(num))
sql="insert into tb1(gender,class_id,sname) values(%s,%s,%s)"
print(obj.exec_sql_many(sql,data)) start=time.time()
job_list=[]
for i in range(10):
job_list.append(gevent.spawn(test_func,100000)) gevent.joinall(job_list) obj.close_conn() print("totol time:",time.time()-start)

显示代码

开启10个连接池插入100W数据的时间:

totol time: 240.16892313957214

开启50个连接池插入100W数据的时间:

totol time: 202.82087111473083

开启100个线程池插入100W数据的时间:

totol time: 196.1710569858551

5.后记

统计结果如下:

单线程一个连接使用时间:978.76s

  10个连接池 50个连接池 100个连接池
多线程版 242.81s 192.49s 191.74s
协程版 240.17s 202.82s 196.17s

通过统计结果显示,通过协程和多线程操作连接池插入相同数据,相对一个连接提升速度明显,但是在将连接池开到50以及100时,性能提升并没有想象中那么大,这时候,瓶颈已经不在网络I/O上了,而在数据库中,mysql在大量连接写入数据时,也会有锁的产生,这时候就需要优化数据库的相关设置了。

在对比中显示多线程利用线程池和协程利用线程池的性能差不多,但是多线程的开销比协程要大。

和大神讨论过,在项目开发中需要考虑到不同情况使用不同的技术,多线程适合使用在连接量较大,但每个连接处理时间很短的情况下,而协程适用于处理大量连接,但同时活跃的链接比较少,并且每个连接的时间量比较大的情况下。

在实际生产应用中,创建连接池可以按需分配,当连接不够用时,在连接池没达到上限的情况下,在连接池里面加入新的连接,在连接池比较空闲的情况下,关闭一些连接,实现这一个操作的原理是通过queue里面的超时时间来控制,当等待时间超过了超时时间时,说明连接不够用了,需要加入新的连接。

杂项之pymysql连接池的更多相关文章

  1. 第一篇:杂项之pymysql连接池

    杂项之pymysql连接池   杂项之pymysql连接池 本节内容 本文的诞生 连接池及单例模式 多线程提升 协程提升 后记 1.本文的诞生 由于前几天接触了pymysql,在测试数据过程中,使用普 ...

  2. pymysql 连接池

    pymysql连接池 import pymysql from DBUtils.PooledDB import PooledDB, SharedDBConnection ''' 连接池 ''' clas ...

  3. python全栈开发day113-DBUtils(pymysql数据连接池)、Request管理上下文分析

    1.DBUtils(pymysql数据连接池) import pymysql from DBUtils.PooledDB import PooledDB POOL = PooledDB( creato ...

  4. Python 使用 PyMysql、DBUtils 创建连接池,提升性能

    转自:https://blog.csdn.net/weixin_41287692/article/details/83413775 Python 编程中可以使用 PyMysql 进行数据库的连接及诸如 ...

  5. MySQL 使用连接池封装pymysql

    备注:1,记得先修改连接的数据库哦,(用navicat更方便一点):2,分开两个py文件写入,运行sqlhelper.py文件 一.在utils.py中写 import pymysqlfrom DBU ...

  6. 连接池的实现 redis例子

    # -*- encoding:utf-8 -*- # import pymysql # # conn = pymysql.connect(host="127.0.0.1", por ...

  7. 利用python list 完成最简单的DB连接池

    先来看查看效果: 在代码连接数据库后,并且执行三条sql后,将mysql直接重启掉,故我们的连接池连接均是不ok的,所以,它会全部删除再抓新的连接下来,重启mysql命令: 关于python代码: # ...

  8. DBUtils--数据库连接池

    介绍 DBUtils是一套Python数据库连接池包,并允许对非线程安全的数据库接口进行线程安全包装. pg大概是是PostgreSQL(基于PyGreSQL)数据库,DB是其他数据库 Steady[ ...

  9. 深入研究sqlalchemy连接池

    简介: 相对于最新的MySQL5.6,MariaDB在性能.功能.管理.NoSQL扩展方面包含了更丰富的特性.比如微秒的支持.线程池.子查询优化.组提交.进度报告等. 本文就主要探索MariaDB当中 ...

随机推荐

  1. Mybats中字符串判断

      <if test=" name=='你好' "> <if> 这样会有问题,换成 <if test=' name=="你好" ' ...

  2. 安装redis入门

    redis官网:redis.io redis版本用的是redis-3.2.2 $ wget http://download.redis.io/releases/redis-3.2.2.tar.gz $ ...

  3. Asp.net mvc自定义Filter简单使用

    自定义Filter的基本思路是继承基类ActionFilterAttribute,并根据实际需要重写OnActionExecuting,OnActionExecuted,OnResultExecuti ...

  4. mysql时间加减函数

    先来看一个例子: select now(),now()+0; 可以看到now()函数可以返回一个时间也可以返回一个数字,就看大家如何使用.如果相对当前时间进行增加或减少,并不能直接加上或减去一个数字而 ...

  5. GPS数据读取与处理

    GPS数据读取与处理 GPS模块简介 SiRF芯片在2004年发布的最新的第三代芯片SiRFstar III(GSW 3.0/3.1),使得民用GPS芯片在性能方面登上了一个顶峰,灵敏度比以前的产品大 ...

  6. LruCache缓存

    LruCache通常用于实现内存缓存,采用的缓存算法是LRU(Least Recently Used)即近期最少使用算法,其核心思想是:当缓存满的时候,会优先淘汰那些近期最少使用的缓存对象. 1.Lr ...

  7. iOS-钥匙串中证书全部失效(证书的签发者无效)的解决办法

    今天用Xcode打包IPA文件给同事,结果提示import时,提示证书missing,找了半天没发现问题,后来打开钥匙串,发现证书全失效了!!!根证书失效了!吓死宝宝了 解决方法 首选此方法: 1.打 ...

  8. OC 类簇与复合

    OC 类簇与复合 类簇: 类簇是Foundation框架中广泛使用的设计模式.类簇将一些私有的.具体的子类组合在一个公共的.抽象的超类下面,以这种方法来组织类可以简化一个面向对象框架的公开架构,而又不 ...

  9. Android Material Design 兼容库的使用

    Android Material Design 兼容库的使用 mecury 前言:近来学习了Android Material Design 兼容库,为了把这个弄懂,才有了这篇博客,这里先推荐两篇博客: ...

  10. 利用split

    java.lang.string.splitsplit 方法将一个字符串分割为子字符串,然后将结果作为字符串数组返回.stringObj.split([separator,[limit]])strin ...