简介:

相对于最新的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

八:继续研究相关代码

http://docs.sqlalchemy.org/en/latest/core/pooling.html?highlight=use_threadlocal#using-connection-pools-with-multiprocessing

使用连接池进行多重处理

http://docs.sqlalchemy.org/en/latest/core/pooling.html?highlight=use_threadlocal#api-documentation-available-pool-implementations

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连接池的更多相关文章

  1. hibernate+mysql的连接池配置

    1:连接池的必知概念    首先,我们还是老套的讲讲连接池的基本概念,概念理解清楚了,我们也知道后面是怎么回事了. 以前我们程序连接数据库的时候,每一次连接数据库都要一个连接,用完后再释放.如果频繁的 ...

  2. c3p0连接池获得的Connection执行close方法后是否真的销毁Connection对象?

    问题描述: jfinal做的api系统中,在正常调用接口一段时间后,突然再调用接口的时候,该请求无响应api系统后台也无错误信息 (就是刚开始接口调用是正常的,突然就无响应了) 于是啊,就开始找错误. ...

  3. druid连接池异常

    在从excel导入10W条数据到mysql中时,运行一段时间就会抛这个异常,连接池问题 org.springframework.transaction.CannotCreateTransactionE ...

  4. 构建简单的socket连接池

    一开始,选用Vector<E>来存放连接.由于这个容器不是并发安全的,于是,每个方法都加一个synchronized来保持并发时的同步操作,并发效率很差,果断放弃.空余时间研究了下多线程的 ...

  5. Mybatis的连接池

    先总结一个原则:mytatis的连接池最大值poolMaximumActiveConnections尽量跟服务器的并发访问量持平以至于大于并发访问量. 原因:在org.apache.ibatis.da ...

  6. HttpClient 4.3连接池参数配置及源码解读

    目前所在公司使用HttpClient 4.3.3版本发送Rest请求,调用接口.最近出现了调用查询接口服务慢的生产问题,在排查整个调用链可能存在的问题时(从客户端发起Http请求->ESB-&g ...

  7. Http持久连接与HttpClient连接池

    一.背景 HTTP协议是无状态的协议,即每一次请求都是互相独立的.因此它的最初实现是,每一个http请求都会打开一个tcp socket连接,当交互完毕后会关闭这个连接. HTTP协议是全双工的协议, ...

  8. springboot添加多数据源连接池并配置Mybatis

    springboot添加多数据源连接池并配置Mybatis 转载请注明出处:https://www.cnblogs.com/funnyzpc/p/9190226.html May 12, 2018  ...

  9. jedis连接池参数minEvictableIdleTimeMillis和softMinEvictableIdleTimeMillis探索

    我们通常在使用JedisPoolConfig进行连接池配置的时候,minEvictableIdleTimeMillis和softMinEvictableIdleTimeMillis这两个参数经常会不懂 ...

随机推荐

  1. vue2.0 axios交互

    vue使用axios交互时候会出现的问题大致有三个: 1:本地调试跨域问题? 2:post请求,传参不成功,导致请求失败? 3:axios引用,在使用的组件里面引用 解决方案: 问题一:跨域? 解决本 ...

  2. 优秀的web工具网址

    1.百度开源的工具 https://www.baidu.com/home/news/data/newspage?nid=3868911095318333105&n_type=0&p_f ...

  3. xlua怎么样hotfix C#中的重写方法???

    问题的来源之这样的: 线上项目遇到一个问题,就是子类 override 了父类的一个 virtual 方法,并且调用到了父类里面的 virtual 方法.现在子类  override 的方法里有一些错 ...

  4. Python全栈开发-Day2-Python基础2

    本节内容 列表.元组操作 字符串操作 字典操作 集合操作 文件操作 字符编码与转码 1. 列表.元组操作 列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储.修改等操作 定义列表 ...

  5. 第 4 章 容器 - 029 - 限制容器的 Block IO

    限制容器的 Block IO Block IO 是另一种可以限制容器使用的资源. Block IO 指的是磁盘的读写,docker 可通过设置权重.限制 bps 和 iops 的方式控制容器读写磁盘的 ...

  6. nodejs中function*、yield和Promise的示例

    var co = require("co"); var fs = require("fs"); function cusReadFile(fileName) { ...

  7. ThinkPHP表单自动验证(注册功能)

    控制器中: 模型中: 视图中:

  8. 让 Ubuntu 16 开机自动启动 Vino Server

    Vino Server 有一个问题, 如果用户没有login , 它是不会启动的. 但是,我把帐号设置从自动启动之后,Vino Server还是没有启动. 看来自动启动跟输密码启动还是有差别的. 具体 ...

  9. English Voice of <<Beautiful now>>

    Beautiful Now  -Zedd & Jon Bellion I see what you're wearing, there's nothing beneath it 我看见了你身着 ...

  10. every day a practice —— morning(4)

    If there’s one thing New Yorkers love more than discovering a new secret remedy, it’s telling other ...