1、场景描述
并发量达到一定数量, 就会导致 数据库的连接数会被瞬时占满。
2、解决方法
<1>安装djorm-ext-pool
pip install djorm-ext-pool
<2>创建一个APP应用
创建一个专门为djorm_pool的App,在init.py文件中添加下面代码
# -*- coding: utf-8 -*-
import logging
from functools import partial
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from sqlalchemy import exc
from sqlalchemy import event
from sqlalchemy.pool import manage
from sqlalchemy.pool import Pool
from sqlalchemy.event import listens_for
POOL_PESSIMISTIC_MODE = getattr(settings, "DJORM_POOL_PESSIMISTIC", False)
POOL_SETTINGS = getattr(settings, 'DJORM_POOL_OPTIONS', {
})
POOL_SETTINGS.setdefault("recycle", 3600)
logger = logging.getLogger('djorm.pool')
@event.listens_for(Pool, "checkout")
def _on_checkout(dbapi_connection, connection_record, connection_proxy):
logger.debug("connection retrieved from pool")
if POOL_PESSIMISTIC_MODE:
cursor = dbapi_connection.cursor()
try:
cursor.execute("SELECT 1")
except:
# raise DisconnectionError - pool will try
# connecting again up to three times before raising.
raise exc.DisconnectionError()
finally:
cursor.close()
@event.listens_for(Pool, "checkin")
def _on_checkin(*args, **kwargs):
logger.debug("connection returned to pool")
@event.listens_for(Pool, "connect")
def _on_connect(*args, **kwargs):
logger.debug("connection created")
def patch_mysql():
class hashabledict(dict):
def __hash__(self<