Home >Backend Development >PHP Tutorial >How to clear MySQL dead connections based on PHP
This article mainly introduces the method of clearing MySQL dead connections in PHP. It implements the checking and clearing function for MySQL dead links by executing PHP scripts regularly. Friends in need can refer to the
connection situation. The main symptom is that there are too many Sleep connections, and the Time is very long, occupying all the available connections, so that other users can no longer connect to the database. I began to consider adjusting the MySQL database parameters, but changed many parameters and still did not solve the problem. So I thought of a more ruthless way to write a php script and execute it every 2 minutes. If a dead connection is found (more than 120 seconds), kill it. In this way, some programs will no longer kill the database server. The following is Kill Small program for dead connections:
kill-mysql-sleep-proc.php:
define('MAX_SLEEP_TIME',120); $hostname="localhost"; $username="root"; $password="password"; $connect=mysql_connect($hostname,$username,$password); $result=mysql_query("SHOWPROCESSLIST",$connect); while($proc=mysql_fetch_assoc($result)){ if($proc["Command"]=="Sleep"&&$proc["Time"]>MAX_SLEEP_TIME){ @mysql_query("KILL".$proc["Id"],$connect); } } mysql_close($connect); ?>
Change $password in it to your actual database password. The time of dead connections can also be modified. . Then just add the scheduled task. For example, use the crontab-e command to add:
*/2****php/usr/local/sbin/kill-mysql-sleep-proc.php
You can check and clear the dead connections in the database every 2 minutes
Summary: The above is the entire content of this article, I hope it can It will be helpful to everyone’s study.
Related recommendations:
Detailed explanation of PHP's CURL method curl_setopt() function case
Detailed explanation of PHP regular matching date and timestamp conversion case
php Detailed explanation of ternary operator examples
The above is the detailed content of How to clear MySQL dead connections based on PHP. For more information, please follow other related articles on the PHP Chinese website!