1) 数据库连接池
连接池基于sqlalchemy的QueuePool, 自己实现了一个基于gevent 的queue的GreenletQueuePool, 协程安全并且get和put操作的时候不会hung住导致获取链接超时
版本约束:
gevent == 1.0.2 -> 1.2a1
sqlalchemy == 0.9.1 -> 1.1.3
django-mysqlpool == 0.2.1(注意这个必须用这个版本, 低版本(pip install 安装的)不支持django的多数据库!!!重要哦)
(下载地址: https://github.com/smartfile/django-mysqlpool)
gevent-queuepool == 1.0.0(下载地址: https://github.com/viphxin/gevent-queuepool)---附件也有
2)配置:
django settings.py
'common':{#通用库
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
#'ENGINE': 'django_mysqlpool.backends.mysqlpool', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'common_game', # Or path to database file if using sqlite3.
'USER': 'sy', # Not used with sqlite3.
'PASSWORD': 'sy123SY', # Not used with sqlite3.
'HOST': mysql_db, # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3308', # Set to empty string for default. Not used with sqlite3.
'AUTOCOMMIT':True,
'CONN_MAX_AGE':0,
'OPTIONS':{"init_command": "SET storage_engine=INNODB;SET sql_mode='STRICT_TRANS_TABLES'", # INNODB MYISAM,前者支持事务和行锁
"use_unicode": True , 'charset': 'utf8'}
},
# -----------fix sqlalchemy 支持线程池(queuepool 并发会超时)
#from common import sqlalchemy_patch
import gevent_queuepool
gevent_queuepool.load()
# -----------fix sqlalchemy 支持线程池
MYSQLPOOL_BACKEND = 'GreenletQueuePool' #StaticPool(一个进程一个链接),QueuePool, GreenletQueuePool
MYSQLPOOL_ARGUMENTS = {
'use_threadlocal': False,
'pool_size': 5,#这个>=1 最大缓存链接数
'max_overflow': 10,#这个>=1 最大可超过的连接数, 也就是说连接数最大可到pool_size + max_overflow, 但是max_overflow用完之后就会关闭不会返回pool
'timeout': 5,#获取链接超时时间
'recycle': 600,#600秒后自动重新获取新的数据库链接, 防止mysql server主动断开
}
3)主动将数据库连接放回pool(重要):
from django_mysqlpool import auto_close_db
@auto_close_db
def api_n:
pass