gpt4 book ai didi

mysql - Django mysql 连接太多

转载 作者:行者123 更新时间:2023-11-29 01:17:19 26 4
gpt4 key购买 nike

我用的是Django和mysql,遇到连接太多的问题。

我从命令行运行 python 脚本,但与 Django 模型集成以检查数据库中的数据。该脚本每 30 秒运行一次,我使用线程来控制它。 My_function 是将检查数据库状态的函数。

while True: 
now = time.time()
if now < next:
time.sleep(next - now)
t = Thread(target=my_function,)
t.start()# start a thread

next += interval

问题出在我监控mysql服务器的时候。一直有大约10个连接,它们都在休眠。我只是不明白为什么。有 2 个事件的 python 线程不断运行,所有其他线程在完成时终止。为什么mysql连接数是10?任何人都可以帮助我吗?非常感谢!

更新 1:现在放上mysql processlist的截图。连接都处于 sleep 模式并且什么都不做,创建连接的线程已经终止。这真的很奇怪。

+------+------+-----------------+----------+---------+-------+-------+------------------+
| Id | User | Host | db | Command | Time | State | Info |
+------+------+-----------------+----------+---------+-------+-------+------------------+
| 411 | root | localhost:47347 | NULL | Sleep | 2 | | NULL |
| 412 | root | localhost:47350 | NULL | Sleep | 3 | | NULL |
| 479 | root | localhost | NULL | Sleep | 27164 | | NULL |
| 918 | root | localhost | EZ_Green | Sleep | 14006 | | NULL |
| 953 | root | localhost | EZ_Green | Sleep | 12956 | | NULL |
| 989 | root | localhost | EZ_Green | Sleep | 11874 | | NULL |
| 1025 | root | localhost | EZ_Green | Sleep | 10796 | | NULL |
| 1061 | root | localhost | EZ_Green | Sleep | 9716 | | NULL |
| 1097 | root | localhost | EZ_Green | Sleep | 8636 | | NULL |
| 1132 | root | localhost | EZ_Green | Sleep | 7586 | | NULL |
| 1168 | root | localhost | EZ_Green | Sleep | 6506 | | NULL |
| 1204 | root | localhost | EZ_Green | Sleep | 5426 | | NULL |
| 1240 | root | localhost | EZ_Green | Sleep | 4346 | | NULL |
| 1276 | root | localhost | EZ_Green | Sleep | 3266 | | NULL |
| 1312 | root | localhost | EZ_Green | Sleep | 2186 | | NULL |
| 1348 | root | localhost | EZ_Green | Sleep | 1106 | | NULL |
| 1384 | root | localhost | EZ_Green | Sleep | 26 | | NULL |
| 1385 | root | localhost | NULL | Query | 0 | NULL | show processlist |
+------+------+-----------------+----------+---------+-------+-------+------------------+

最佳答案

正如尘土飞扬所说,

Every thread that uses Django ORM creates a new database connection. And Django will not manage the connection automatically that created by your own thread. So you should manage it.

您可以在每个线程退出之前简单地执行此操作:

from django.db import connection

# your work thread method

def my_function():
# do something...
# close the db connection explicitly

connection.close()

关于mysql - Django mysql 连接太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14592729/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com