グローバル変数を使用して持続的接続を実装する小さなカスタムpsycopg2バックエンドを作成しました。これにより、1秒あたりのリクエスト数を350から1600に改善することができました(選択がほとんどない非常に単純なページで)base.py
任意のディレクトリ(postgresql_psycopg2_persistentなど)で呼び出され、設定で設定されたファイルに保存するだけです
DATABASE_ENGINEからprojectname.postgresql_psycopg2_persistent
ノート!!!コードはスレッドセーフではありません-予期しない結果が発生するため、Pythonスレッドでは使用できません。mod_wsgiの場合は、threads=1でpreforkデーモンモードを使用してください。
# Custom DB backend postgresql_psycopg2 based
# implements persistent database connection using global variable
from django.db.backends.postgresql_psycopg2.base import DatabaseError, DatabaseWrapper as BaseDatabaseWrapper, \
IntegrityError
from psycopg2 import OperationalError
connection = None
class DatabaseWrapper(BaseDatabaseWrapper):
def _cursor(self, *args, **kwargs):
global connection
if connection is not None and self.connection is None:
try: # Check if connection is alive
connection.cursor().execute('SELECT 1')
except OperationalError: # The connection is not working, need reconnect
connection = None
else:
self.connection = connection
cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)
if connection is None and self.connection is not None:
connection = self.connection
return cursor
def close(self):
if self.connection is not None:
self.connection.commit()
self.connection = None
または、これはスレッドセーフなスレッドですが、Pythonスレッドは複数のコアを使用しないため、前のスレッドのようにパフォーマンスが向上することはありません。これはマルチプロセスのものでも使用できます。
# Custom DB backend postgresql_psycopg2 based
# implements persistent database connection using thread local storage
from threading import local
from django.db.backends.postgresql_psycopg2.base import DatabaseError, \
DatabaseWrapper as BaseDatabaseWrapper, IntegrityError
from psycopg2 import OperationalError
threadlocal = local()
class DatabaseWrapper(BaseDatabaseWrapper):
def _cursor(self, *args, **kwargs):
if hasattr(threadlocal, 'connection') and threadlocal.connection is \
not None and self.connection is None:
try: # Check if connection is alive
threadlocal.connection.cursor().execute('SELECT 1')
except OperationalError: # The connection is not working, need reconnect
threadlocal.connection = None
else:
self.connection = threadlocal.connection
cursor = super(DatabaseWrapper, self)._cursor(*args, **kwargs)
if (not hasattr(threadlocal, 'connection') or threadlocal.connection \
is None) and self.connection is not None:
threadlocal.connection = self.connection
return cursor
def close(self):
if self.connection is not None:
self.connection.commit()
self.connection = None