1

当使用 Gunicorn 与多个进程/工作人员一起运行 Django 时,我的一些手动 MySQL 数据库事务遇到了死锁问题。

DatabaseError(1205, 'Lock wait timeout exceeded; try restarting transaction')

我的设置使用多个数据库,并且我的函数需要在调用时传递给数据库才能使用。出于这个原因,我不能使用标准的Django 事务装饰器,因为 db 需要硬编码为参数。我检查了装饰器代码以了解事务是如何管理的,我的函数如下所示:

from django.db import connections

def process(self, db, data):

    # Takeover transaction management
    connections[db].enter_transaction_management(True)
    connections[db].managed(True)

    # Process
    try:
        # do things with my_objects...
        for obj in my_objects:
            obj.save(using=db)
        connections[db].commit()
    except Exception as e:
        connections[db].rollback()
    finally:
        connections[db].leave_transaction_management()

谁能发现这里可能出了什么问题?

4

1 回答 1

4

请注意,您可能希望使用更清晰的with-style 语法。以下应该与您上面的代码相同,但更 pytonic。

from django.db import transaction
from __future__ import with_statement

def process(self, db, data):

    with transaction.commit_on_success(using=db):
        # do things with my_objects...
        for obj in my_objects:
            obj.save(using=db)

或与装饰师

from django.db import transaction

@transaction.commit_on_success(using=db)
def process(self, db, data):    

    # do things with my_objects...
    for obj in my_objects:
        obj.save(using=db)

但是,这并不能解决您的死锁问题..

您可能会成功降低事务隔离级别。mysql 上的默认设置REPEATABLE READ对于大多数用途来说太严格了。(oracle 默认为READ COMMITTED')

您可以通过将其添加到您的settings.py

MYSQL_DATABASE_OPTIONS = {'init_command': 'SET storage_engine=INNODB; SET 
                 SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;'}

DATABASES = {
  'default': {  # repeat for each db
       'ENGINE':  ... etc
       ...
       ...
       'OPTIONS': MYSQL_DATABASE_OPTIONS
      }
  }
于 2013-03-05T20:10:58.053 回答