深入研究sqlalchemy连接池
简介:
相对于最新的MySQL5.6,MariaDB在性能、功能、管理、NoSQL扩展方面包含了更丰富的特性。比如微秒的支持、线程池、子查询优化、组提交、进度报告等。
本文就主要探索MariaDB当中连接池的一些特性,配置。来配合我们的sqlalchemy。
一:起因
本来是不会写这个东西的,但是,写好了python--flask程序,使用sqlalchemy+mariadb,部署以后总是出问题,500错误之类的。
使用默认连接参数
engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan',)
错误提示是:
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available. [SQL: 'SELECT public.id AS public_id, public.public_name AS public_public_name, public.public_email AS public_public_email \nFROM public \nWHERE public.public_name = %(public_name_1)s \n LIMIT %(param_1)s'] [parameters: [{}]] (Background on this error at: http://sqlalche.me/e/e3q8)
http://sqlalche.me/e/e3q8:
OperationalError:
Exception raised for errors that are related to the database’s operation andnot necessarily under the control of the programmer, e.g. an unexpecteddisconnect occurs, the data source name is not found, a transaction could notbe processed, a memory allocation error occurred during processing, etc.
This error is aDBAPI Errorand originates fromthe database driver (DBAPI), not SQLAlchemy itself.
TheOperationalErroris the most common (but not the only) error class usedby drivers in the context of the database connection being dropped, or notbeing able to connect to the database. For tips on how to deal with this, seethe sectionDealing with Disconnects.
意思是没有正确断开和数据库的连接。
二:处理断开
http://docs.sqlalchemy.org/en/latest/core/pooling.html#pool-disconnects
官方给了三种方案来解决这个问题:
1.悲观处理
engine = create_engine("mysql+pymysql://user:pw@host/db", pool_pre_ping=True)
pool_pre_ping=True
表示每次连接从池中检查,如果有错误,监测为断开的状态,连接将被立即回收。
2.自定义悲观的ping
from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy import select some_engine = create_engine(...) @event.listens_for(some_engine, "engine_connect")
def ping_connection(connection, branch):
if branch:
# "branch" refers to a sub-connection of a connection,
# we don't want to bother pinging on these.
return # turn off "close with result". This flag is only used with
# "connectionless" execution, otherwise will be False in any case
save_should_close_with_result = connection.should_close_with_result
connection.should_close_with_result = False try:
# run a SELECT 1. use a core select() so that
# the SELECT of a scalar value without a table is
# appropriately formatted for the backend
connection.scalar(select([1]))
except exc.DBAPIError as err:
# catch SQLAlchemy's DBAPIError, which is a wrapper
# for the DBAPI's exception. It includes a .connection_invalidated
# attribute which specifies if this connection is a "disconnect"
# condition, which is based on inspection of the original exception
# by the dialect in use.
if err.connection_invalidated:
# run the same SELECT again - the connection will re-validate
# itself and establish a new connection. The disconnect detection
# here also causes the whole connection pool to be invalidated
# so that all stale connections are discarded.
connection.scalar(select([1]))
else:
raise
finally:
# restore "close with result"
connection.should_close_with_result = save_should_close_with_result
说实话,没怎么看明白。
像是try一个select 语句,如果没问题就关闭。
3.乐观处理
from sqlalchemy import create_engine, exc
e = create_engine(...)
c = e.connect() try:
# suppose the database has been restarted.
c.execute("SELECT * FROM table")
c.close()
except exc.DBAPIError, e:
# an exception is raised, Connection is invalidated.
if e.connection_invalidated:
print("Connection was invalidated!") # after the invalidate event, a new connection
# starts with a new Pool
c = e.connect()
c.execute("SELECT * FROM table")
这个看懂了,try一个select语句,如果无效,就返回Connection was invalidated!,然后开一个新的连接,再去执行select。这个应该写个装饰器,放在每个查询前面。
4.使用连接池回收
from sqlalchemy import create_engine
e = create_engine("mysql://scott:tiger@localhost/test", pool_recycle=3600)
这种方式就比较简单了,在连接参数中写上连接超时时间即可。
5.这是自己看文档找到的方法
from sqlalchemy.pool import QueuePool,NullPool,AssertionPool,StaticPool,SingletonThreadPool,Pool
在sqlalchemy.pool下有已经配置好的连接池,直接使用这些连接池也应该可以。
三:测试
docker run --restart=always --privileged --name My_mariadb_01 -p 3301:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_02 -p 3302:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_03 -p 3303:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_04 -p 3304:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_05 -p 3305:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
为避免因数据库交叉连接,首先开启5个MARIADB
Flask_Plan_01 8801 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan',)
Flask_Plan_02 8802 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', pool_pre_ping=True)
Flask_Plan_03 8803 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=QueuePool)
Flask_Plan_04 8804 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=NullPool)
Flask_Plan_05 8805 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', pool_recycle=3600)
用这5种连接参数进行连接测试。
如果你愿意,也可以继续开,QueuePool,NullPool,AssertionPool,StaticPool,SingletonThreadPool,Pool,把这几种都测试一下。
8801 8805 均会不同程度的出现500错误,8801频率还高点。
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available. [SQL: 'SELECT public.id AS public_id, public.public_name AS public_public_name, public.public_email AS public_public_email \nFROM public \nWHERE public.public_name = %(public_name_1)s \n LIMIT %(param_1)s'] [parameters: [{}]] (Background on this error at: http://sqlalche.me/e/e3q8)
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available. [SQL: 'SELECT public.id AS public_id, public.public_name AS public_public_name, public.public_email AS public_public_email \nFROM public \nWHERE public.public_name = %(public_name_1)s \n LIMIT %(param_1)s'] [parameters: [{}]] (Background on this error at: http://sqlalche.me/e/e3q8)
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
等会儿看看8802 8803 8804如何。
四:深入研究sqlalchemy源码
VENV\Flask_Base\Lib\site-packages\sqlalchemy\engine\__init__.py

看起来,没有默认值。所以engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan',)报错频率比较高。
五:研究pool源码
VENV\Flask_Base\Lib\site-packages\sqlalchemy\pool.py

看来poolclass的类型都定义在这里了。
1.SingletonThreadPool
A Pool that maintains one connection per thread
每个线程维护一个连接的池。

2.QueuePool
A :class:`.Pool` that imposes a limit on the number of open connections.
这种方式限制了连接数量,QueuePool是默认的连接池方式,除非使用了方言,也就是第三方链接库。
难怪我使用MySQL-connector-python时老出错呢,没打开连接池啊。

3.NullPool
A Pool which does not pool connections...
不使用连接池

4.StaticPool
A Pool of exactly one connection, used for all requests.
一个完整的连接池,用于所有的连接。

5.AssertionPool
A :class:`.Pool` that allows at most one checked out connection at any given time.
任何时间只给一个签出连接?为了debug模式?不懂了。

看的官方说明也没这么详细。
这么看来,如果我使用默认链接库,可以不加参数试试。
mysql-python是sqlalchemy默认的mysql链接库,我在windows下装不上。放弃测试默认链接库,手动指定连接池为QueuePool。
或者指定连接池类型为:QueuePool StaticPool SingletonThreadPool(多线程的时候)
六:连接池类型测试
修改测试docker
docker run --restart=always --privileged --name My_mariadb_01 -p 3301:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_02 -p 3302:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_03 -p 3303:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_04 -p 3304:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_05 -p 3305:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
docker run --restart=always --privileged --name My_mariadb_06 -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mariadb:10.2.13
Flask_Plan_01 8801 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', pool_pre_ping=True))
Flask_Plan_02 8802 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=SingletonThreadPool)
Flask_Plan_03 8803 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=QueuePool)
Flask_Plan_04 8804 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=NullPool)
Flask_Plan_05 8805 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=StaticPool)
Flask_Plan_06 8806 engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan', poolclass=AssertionPool)
七:编写测试脚本
import requests
import time
i = 1
while True:
try:
r=requests.get('http://192.168.0.104:8801',timeout=5)
if r.status_code==200:
print(time.strftime('%Y-%m-%d %H:%M:%S')+'---'+str(i)+'---'+str(r.status_code)+'---ok')
else:
print(time.strftime('%Y-%m-%d %H:%M:%S') + '---' + str(i) + '---' + str(r.status_code) + '-----------badr')
break
time.sleep(1)
i+=1
except:
print('except')
print(time.strftime('%Y-%m-%d %H:%M:%S') +'---'+str(i)+'-----------bad')
break
修改地址,把几个测试服务都开始跑。
出错就会停了。
代码很烂,凑活测试而已。
从晚上22:30睡觉到早上6:10起床,pool_pre_ping=True,SingletonThreadPool,QueuePool,NullPool,StaticPool,AssertionPool,都很稳定,访问代码都是200
八:继续研究相关代码
使用连接池进行多重处理
api文档--连接池的实现
classsqlalchemy.pool.Pool(creator,recycle=-1,echo=None,use_threadlocal=False,logging_name=None,reset_on_return=True,listeners=None,events=None,dialect=None,pre_ping=False,_dispatch=None)
Parameters:
creator–可调用的函数返回对象。
recycle– 超时回收时间。如果连接超过这个时间,连接就被关闭,换一个新的连接
logging_name - 日志标识名称
echo– 是否打印sql语句
use_threadlocal–是否使用线程,在同一应用程序的线程使用相同的连接对象
reset_on_return–在返回前的操作
rollback,大概是自动回滚
True 同为回滚
commit 大概是自动提交的意思
None 无操作
none 无操作
False 无操作
events– 列表元组,每个表单会传递给listen………………没搞懂
listeners - 弃用,被listen取代
dialect–链接库,使用create_engine时不使用,由引擎创建时处理
pre_ping–是否测试连接
基本上这些参数都在engine-creation-api中
http://docs.sqlalchemy.org/en/rel_1_0/core/engines.html#engine-creation-api
Pool (creator,recycle=-1,echo=None,use_threadlocal=False,logging_name=None,reset_on_return=True,listeners=None,events=None,dialect=None,pre_ping=False,_dispatch=None)
StaticPool (creator,recycle=-1,echo=None,use_threadlocal=False,logging_name=None,reset_on_return=True,listeners=None,events=None,dialect=None,pre_ping=False,_dispatch=None)
NullPool (creator,recycle=-1,echo=None,use_threadlocal=False,logging_name=None,reset_on_return=True,listeners=None,events=None,dialect=None,pre_ping=False,_dispatch=None)
QueuePool (creator,pool_size=5,max_overflow=10,timeout=30,**kw)
SingletonThreadPool(creator,pool_size=5,**kw)
AssertionPool (*args,**kw)
这下清楚了,Pool,StaicPool,NullPool,都一样,直接回收,效率一定低了。
我们就指定默认的QueuePool好了。以后观察着服务器的负载,负载大了以后,调整就好了。
自定义方法如下:
engine = create_engine('mysql+mysqlconnector://plan:plan@mysql/plan',
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_pre_ping=True)
九:总结
曲折的道路,终于找到了解决方案。
sqlalchemy的教程当中,很少有讲如何部署的。很多又是linux开发。可能在linux下很容易装默认链接库,部署的时候就自动使用了QueuePool连接池。所以这种问题很少出现。
我在windows下开发,部署在linux,开发和部署都使用了非默认链接库,导致没有使用默认连接池。
那么随着深入研究,找到了连接池的配置,并掌握这一知识,为以后的开发部署工作,扫除了障碍。
虽然源码里面还有很多看不懂,但是读书百遍其义自见,还是要多读(我是懒蛋,遇到问题,再去解决,下一个问题是什么呢?)。
深入研究sqlalchemy连接池的更多相关文章
- hibernate+mysql的连接池配置
1:连接池的必知概念 首先,我们还是老套的讲讲连接池的基本概念,概念理解清楚了,我们也知道后面是怎么回事了. 以前我们程序连接数据库的时候,每一次连接数据库都要一个连接,用完后再释放.如果频繁的 ...
- c3p0连接池获得的Connection执行close方法后是否真的销毁Connection对象?
问题描述: jfinal做的api系统中,在正常调用接口一段时间后,突然再调用接口的时候,该请求无响应api系统后台也无错误信息 (就是刚开始接口调用是正常的,突然就无响应了) 于是啊,就开始找错误. ...
- druid连接池异常
在从excel导入10W条数据到mysql中时,运行一段时间就会抛这个异常,连接池问题 org.springframework.transaction.CannotCreateTransactionE ...
- 构建简单的socket连接池
一开始,选用Vector<E>来存放连接.由于这个容器不是并发安全的,于是,每个方法都加一个synchronized来保持并发时的同步操作,并发效率很差,果断放弃.空余时间研究了下多线程的 ...
- Mybatis的连接池
先总结一个原则:mytatis的连接池最大值poolMaximumActiveConnections尽量跟服务器的并发访问量持平以至于大于并发访问量. 原因:在org.apache.ibatis.da ...
- HttpClient 4.3连接池参数配置及源码解读
目前所在公司使用HttpClient 4.3.3版本发送Rest请求,调用接口.最近出现了调用查询接口服务慢的生产问题,在排查整个调用链可能存在的问题时(从客户端发起Http请求->ESB-&g ...
- Http持久连接与HttpClient连接池
一.背景 HTTP协议是无状态的协议,即每一次请求都是互相独立的.因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接. HTTP协议是全双工的协议, ...
- springboot添加多数据源连接池并配置Mybatis
springboot添加多数据源连接池并配置Mybatis 转载请注明出处:https://www.cnblogs.com/funnyzpc/p/9190226.html May 12, 2018 ...
- jedis连接池参数minEvictableIdleTimeMillis和softMinEvictableIdleTimeMillis探索
我们通常在使用JedisPoolConfig进行连接池配置的时候,minEvictableIdleTimeMillis和softMinEvictableIdleTimeMillis这两个参数经常会不懂 ...
随机推荐
- lua --- 局部变量
1.block(代码块) --- 一个控制结构.一个函数体.一个chunk chunck --- 变量被声明的那个文件或者文本串 2.局部变量只在声明的那个block中有效 3.可以使用 do . ...
- how-to-view-source-of-chrome-extension
https://gist.github.com/paulirish/78d6c1406c901be02c2d Option 1: Command-line download extension as ...
- mysqlsh : mysql shell tutorial
MySQL Shell 是一个高级的命令行客户端以及代码编辑器for Mysql. 除了SQL,MySQL Shell也提供脚本能力 for JS and Python. When MySQL she ...
- ChIP-seq实战 | 染色质免疫共沉淀技术 | ATAC-seq | 染色质开放性测序技术
参考:生信技能树 ChIP-Seq综述 一些简单的copy,纯属个人笔记. ChIP-seq的原理 用于在全基因组范围中研究DNA结合蛋白(相互反应).组蛋白修饰(表观遗传标记)和核小体的技术,研究这 ...
- English trip Spoken English & Word List(updating...)
Word List 词汇 Square 英 [skweə] 美 [skwɛr] adj. 平方的:正方形的:直角的:正直的. 使成方形:与…一致 vi. 一致:成方形 n. 平方:广场:正方形 ...
- Linux中sudo的用法
一.用户在/etc/sudoers文件中的写法语法规则:授权用户 主机=命令动作 这三个要素缺一不可,但在动作之前也可以指定切换到特定用户下,在这里指定切换的用户要用括号括起来,如果不需要密码直接运行 ...
- 20180518VSTO多簿单表汇总
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsof ...
- android -------- ConstraintLayout Guideline和Barrier(四)
前面的文章 ConstraintLayout 介绍 (一) ConstraintLayout约束属性 (二) ConstraintLayout 宽高比和偏移量比(三) 此博文主要讲解:Guidelin ...
- SQL SERVER 字符合并多行为一列
[字符合并多行为一列] 思路1:行转列,在与字符拼接(适用每组列数名相同) 思路2:转xml,去掉多余字符(适用所有) 假设兴趣表Hobbys Name Hobby 小张 打篮球 小张 踢足球 Nam ...
- web功能模块测试用例(模板)
web功能模块测试用例(模板): https://wenku.baidu.com/view/4ada3464ddccda38376baff8.html 如图所示: