[转载]tornado.database添加PooledDB连接池功能
2015-11-24 14:03
302 查看
转载自 http://chenxiaoyu.org/2009/12/01/python-tornado-dbutil.html
tornado.database模块简单包装了下对MySQL的操作,短小精悍。
无奈源码中无连接池功能,遂加上了一段DBUtils模块功能。主要修改了reconnect()方法,大致在database.py第86行左右。(tornado 0.2 win版)
原代码如下:
def reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() self._db = MySQLdb.connect(**self._db_args) self._db.autocommit(True)
修改后:
def reconnect(self): """Closes the existing database connection and re-opens it.""" self.close() try: from DBUtils import PooledDB pool_con = PooledDB.PooledDB(creator=MySQLdb, **self._db_args) self._db = pool_con.connection() except: self._db = MySQLdb.connect(**self._db_args) self._db.autocommit(True)
至于安装DBUtils模块可以去http://pypi.python.org/pypi/DBUtils/下载,也可以简单的用easy_install:
easy_install -U DBUtils
PooledDB有这么几个参数:
* creator 可以生成 DB-API 2 连接的任何函数或 DB-API 2 兼容的数据库连接模块。 * mincached 启动时开启的空连接数量(缺省值 0 意味着开始时不创建连接) * maxcached 连接池使用的最多连接数量(缺省值 0 代表不限制连接池大小) * maxshared 最大允许的共享连接数量(缺省值 0 代表所有连接都是专用的) * maxconnections 最大允许连接数量(缺省值 0 代表不限制) * blocking 设置在达到最大数量时的行为(缺省值 0 或 False) * maxusage 单个连接的最大允许复用次数(缺省值 0 或 False 代表不限制的复用) * setsession: 一个可选的SQL命令列表用于准备每个会话,如 ["set datestyle to german", ...]
creator 函数或可以生成连接的函数可以接受这里传入的其他参数,例如主机名、数据库、用户名、密码等。你还可以选择传入creator函数的其他参数,允许失败重连和负载均衡。
具体可以参照下:http://www.webwareforpython.org/DBUtils/Docs/UsersGuide.zh.html
Published on December 01, 2009.
相关文章推荐
- android国际化(多语言)
- [SQL]查询表里的字段名
- spring3.1中@ResponseBody返回中文乱码
- 详解logstash+elasticsearch+kibana快速搭建日志平台
- 替换文本
- 系统调用日志收集程序_x86_64环境3.14版本内核
- JavaScript的this词法
- Oracle sql 性能优化调整
- httpClient例子详解
- Java SE复习笔记65
- HDU-5157Harry and magic string
- CSS 初识
- poj1734Sightseeing trip【floyd+最小环+路径记录】
- Wireshark实战分析之IP协议(二)
- ios使用kvc机制简化对json的解析
- android知识点杂锦
- android studio生成aar包并在其他工程引用aar包
- USB设备访问管理
- 详解logstash+elasticsearch+kibana快速搭建日志平台
- oracle SQL性能优化