"Broken pipe" 错误通常表示 PHP 与 MySQL 服务器之间的连接意外中断。以下是可能的原因和解决方案:
// 在连接时设置超时参数
$mysqli = new mysqli('host', 'user', 'password', 'database');
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10); // 10秒连接超时
$mysqli->options(MYSQLI_OPT_READ_TIMEOUT, 30); // 30秒读取超时
function queryWithRetry($mysqli, $query, $maxRetries = 3) {
$retryCount = 0;
while ($retryCount < $maxRetries) {
try {
$result = $mysqli->query($query);
if ($result !== false) {
return $result;
}
// 检查连接是否有效
if (!$mysqli->ping()) {
$mysqli->close();
$mysqli = new mysqli('host', 'user', 'password', 'database');
$retryCount++;
continue;
}
// 其他错误
throw new Exception($mysqli->error);
} catch (Exception $e) {
if (strpos($e->getMessage(), 'Broken pipe') !== false) {
$retryCount++;
usleep(500000); // 等待0.5秒再重试
continue;
}
throw $e;
}
}
throw new Exception("Query failed after $maxRetries retries");
}
在 MySQL 配置文件中 (my.cnf/my.ini) 调整以下参数:
[mysqld]
wait_timeout = 28800 # 默认8小时,可适当增大
interactive_timeout = 28800
max_allowed_packet = 256M # 增大数据包大小限制
$mysqli = new mysqli('p:host', 'user', 'password', 'database');
注意:持久连接可能导致资源泄漏,需谨慎使用。
$mysqli->ping()
定期检查连接状态通过以上方法,您应该能够有效解决 "Broken pipe" 错误并提高应用程序的稳定性。