我目前在webfaction中有一个运行MySQL的应用程序。该数据库是一个私有(private)数据库,每隔12个小时左右,我会间歇性地收到“连接过多”错误。

所以我以root身份登录到mysql,以检查事件连接数

mysql> show status like '%onn%';
+--------------------------------+-------+
| Variable_name                  | Value |
+--------------------------------+-------+
| Aborted_connects               | 4     |
| Com_enable_governor_reconn     | 0     |
| Com_enable_governor_reconn_lve | 0     |
| Connections                    | 12    |
| Max_used_connections           | 1     |
| Ssl_client_connects            | 0     |
| Ssl_connect_renegotiates       | 0     |
| Ssl_finished_connects          | 0     |
| Threads_connected              | 1     |
+--------------------------------+-------+

请注意,Max_used_connections = 1(??? !!!)很奇怪。好的,所以流程可能有问题...
mysql> show processlist;
+----+------+-----------------+------+---------+------+-------+------------------+
| Id | User | Host            | db   | Command | Time | State | Info             |
+----+------+-----------------+------+---------+------+-------+------------------+
| 12 | root | localhost:38884 | NULL | Query   |    0 | NULL  | show processlist |
+----+------+-----------------+------+---------+------+-------+------------------+
1 row in set (0.00 sec)

或将最大连接数设置为无法解释的低数字...
mysql> show variables like 'max_connections';
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 151   |
+-----------------+-------+
1 row in set (0.00 sec)

所以我放弃了。这似乎是A)我遇到了那些真正难以理解的错误之一,或者B)我需要休假。

有人有主意吗?

谢谢。

编辑:发现问题

该问题是由使用cron运行的后台任务中的for object in Model.object.iterator()循环引起的。事实证明,屈服和连接正确关闭存在问题。将其更改为.all(),它可以正常工作。

获得的经验教训:1)避免将.iterator()与后台任务一起使用; 2)尽可能避免将App数据库用于后台任务。

最佳答案

我通过在django应用程序settings.py文件中增加MySQL允许的最大连接数来解决此问题。更多信息
MySQL docs

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': '',
    'USER': '',
    'PASSWORD': '',
    'HOST': 'localhost',
    'PORT': '3306',
    'OPTIONS': {
           "init_command": "SET GLOBAL max_connections = 100000", #<-- The fix
    }
  }
}

关于mysql - 在Django 1.4.20中不断获取 'Too many connections',我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30420148/

10-12 22:03
查看更多