twisted的连接池能够大大提高数据库的操作速度,不过最近遇到一个问题很困扰
pymysql.err.InterfaceError: (0, '')
查阅资料得知是因为数据库抛出异常后关闭了数据库没有重连,有了方向,接着去找重连方案。
- 这篇重写了方法,不太适合我的情况。Twisted MySQL: 处理重连,屏蔽日志中输出的异常信息
- 查看api,发现有个
reconnect
,默认False
,加进去,运行,果然不行。。
class ConnectionPool:
"""
Represent a pool of connections to a DB-API 2.0 compliant database.
@ivar connectionFactory: factory for connections, default to L{Connection}.
@type connectionFactory: any callable.
@ivar transactionFactory: factory for transactions, default to
L{Transaction}.
@type transactionFactory: any callable
@ivar shutdownID: L{None} or a handle on the shutdown event trigger which
will be used to stop the connection pool workers when the reactor
stops.
@ivar _reactor: The reactor which will be used to schedule startup and
shutdown events.
@type _reactor: L{IReactorCore} provider
"""
CP_ARGS = "min max name noisy openfun reconnect good_sql".split()
noisy = False # If true, generate informational log messages
min = 3 # Minimum number of connections in pool
max = 5 # Maximum number of connections in pool
name = None # Name to assign to thread pool for debugging
openfun = None # A function to call on new connections
reconnect = False # Reconnect when connections fail
good_sql = 'select 1' # A query which should always succeed
running = False # True when the pool is operating
connectionFactory = Connection
transactionFactory = Transaction
# Initialize this to None so it's available in close() even if start()
# never runs.
shutdownID = None
- 翻文档 twisted.enterprise.adbapi.ConnectionPool
要加cp_前缀。。。
def __init__(self, dbapiName, *connargs, **connkw): (source)
Create a new ConnectionPool.
Any positional or keyword arguments other than those documented here are passed to the DB-API object when connecting. Use these arguments to pass database names, usernames, passwords, etc.
Parameters dbapiName an import string to use to obtain a DB-API compatible module (e.g. 'pyPgSQL.PgSQL')
cp_min the minimum number of connections in pool (default 3)
cp_max the maximum number of connections in pool (default 5)
cp_noisy generate informational log messages during operation (default False)
cp_openfun a callback invoked after every connect() on the underlying DB-API object. The callback is passed a new DB-API connection object. This callback can setup per-connection state such as charset, timezone, etc.
cp_reconnect detect connections which have failed and reconnect (default False). Failed connections may result in ConnectionLost exceptions, which indicate the query may need to be re-sent.
cp_good_sql an sql query which should always succeed and change no state (default 'select 1')
cp_reactor use this reactor instead of the global reactor (added in Twisted 10.2). (type: IReactorCore provider)
完美解决