Skip to content

Latest commit

 

History

History
120 lines (100 loc) · 2.6 KB

1.配置数据库连接.md

File metadata and controls

120 lines (100 loc) · 2.6 KB

配置数据库连接

1.常用配置参数

  • ENGINE: str
    • 驱动模块路径
  • NAME: str
    • 数据库名
  • HOST: str
    • 主机名或域名
  • PORT: Union[str, int]
    • 端口号
  • USER: str
    • 用户名
  • PASSWORD: str
    • 密码
  • CONN_MAX_AGE: Optional[int] = 0
    • 0: 短连接
    • None: 不推荐,永久长连接
    • n: 推荐,n秒后断开的长连接,要小于mysql配置 wait_timeout
    • 注意:gevent部署环境需要使用连接池,不要指定CONN_MAX_AGE
  • OPTIONS
    • charset: str

      • 连接使用的字符集,推荐使用utf8mb4
    • init_command: str

      • 连接时使用的初始命令,推荐设置 RC事务隔离级别
      • mysql默认使用RR隔离级别,区间锁降低并发,增加死锁出现概率
      DATABASES = {
          ...
          OPTIONS: {
              ...
              'init_command': 'set session transaction_isolation = "READ-COMMITTED"'
          }
      }
      

2.pymysql打猴子补丁

# proj/__init__.py

import pymysql

pymysql.install_as_MySQLdb()

3.非gevent部署配置

  • 示例
# proj/settings/production.py

# 数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': '',
        'HOST': '',
        'PORT': '3306',
        'USER': '',
        'PASSWORD': '',
        'CONN_MAX_AGE': 60 * 60 * 2,
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': 'set session transaction_isolation = "READ-COMMITTED"'
        }
    }
}

4.gevent部署配置

  • 使用 django_mysql_geventpool 模块配置连接池

  • 注意:使用连接池,不要指定CONN_MAX_AGE

  • django_mysql_geventpool 参数

    • MAX_CONNS: int
      • 最大连接数
    • MAX_LIFETIME: int
      • n秒后释放连接,要小于mysql配置 wait_timeout
  • 示例

# proj/settings/production.py

from .base import *

INSTALLED_APPS += [
    'django_mysql_geventpool',
    'app_xxx',
    ...
]

# django_mysql_geventpool
GEVENT_POOL = {
    'MAX_CONNS': 25,  # 最大连接数
    'MAX_LIFETIME': 2 * 60 * 60,  # 连接时间
}

# 数据库配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': '',
        'HOST': '',
        'PORT': '3306',
        'USER': '',
        'PASSWORD': '',
        'OPTIONS': {
            'charset': 'utf8mb4',
            'init_command': 'set session transaction_isolation = "READ-COMMITTED"',
            **GEVENT_POOL
        }
    }
}