MySQL server has gone away 错误解析与排查
当 MySQL 返回 `ERROR : (2006, 'MySQL server has gone away')` 时,意味着客户端与 MySQL 服务器之间的网络连接已经断开。
引发此问题的主要原因通常是 SQL 操作耗时过长,或者传输的数据量过大(例如执行过长的 `INSERT ... VALUES` 语句)。针对数据量过大的情况,可以通过调整 `max_allowed_packet` 配置参数来解决,也可以在应用程序中将大数据分批插入。
导致这一错误的因素多样,以下总结网络上的主要分析观点:
原因一:MySQL 服务意外宕机。
判断是否为此原因的方法很简单,进入 MySQL 控制台后,查看 MySQL 的运行时长。
```sql mysql> show global status like 'uptime'; +---------------+---------+ | Variable_name | Value | +---------------+---------+ | Uptime | 3414707 | +---------------+---------+ ``` 1 row in set
1 row in set或者查看MySQL的报错日志,看看有没有重启的信息
如果 `Uptime` 数值很大,表明 MySQL 服务已运行较长时间,说明近期未重启。若日志中也无相关重启信息,则排除此原因,可继续检查其他项。
原因二:MySQL 连接超时。
即某个 MySQL 长连接在很长时间内没有发起新请求,达到了服务端设置的 timeout 阈值,从而被服务端强制关闭。此后若仍使用该连接发起查询,就会报错 `server has gone away`(大多数 PHP 脚本属于此类情况)。
```sql mysql> show global variables like '%timeout'; +----------------------------+----------+ | Variable_name | Value | +----------------------------+----------+ | connect_timeout | 10 | | delayed_insert_timeout | 300 | | innodb_lock_wait_timeout | 50 | | innodb_rollback_on_timeout | OFF | | interactive_timeout | 28800 | | lock_wait_timeout | 31536000 | | net_read_timeout | 30 | | net_write_timeout | 60 | | slave_net_timeout | 3600 | | wait_timeout | 28800 | +----------------------------+----------+ 10 rows in set ``` 10 rows in set
`wait_timeout` 默认为 28800 秒,即 MySQL 连接在无操作 28800 秒后会被自动关闭。
原因三:MySQL 请求连接进程被主动 Kill。
这种情况与原因二相似,区别在于一个是人为手动终止,另一个是 MySQL 自身的超时动作。
```sql mysql> show global status like 'com_kill'; +---------------+-------+ | Variable_name | Value | +---------------+-------+ | Com_kill | 21 | +---------------+-------+ 1 row in set ``` 1 row in set。原因四:SQL 语句过大。
当查询结果集的大小超过 `max_allowed_packet` 的限制时,也会出现此类报错。定位方法是捕获并打印出相关的报错语句。
可以使用 `SELECT * INTO OUTFILE` 的方式将数据导出到文件,检查文件大小是否超过 `max_allowed_packet` 的限制。如果超出,则需要调整参数或优化 SQL 语句。
```sql mysql> show global variables like 'max_allowed_packet'; +--------------------+---------+ | Variable_name | Value | +--------------------+---------+ | max_allowed_packet | 1048576 | +--------------------+---------+ 1 row in set (0.00 sec) 修改参数: ``` 1 row in set (0.00 sec)
```sql mysql> set global max_allowed_packet=1024*1024*16; mysql> show global variables like 'max_allowed_packet'; +--------------------+----------+ | Variable_name | Value | +--------------------+----------+ | max_allowed_packet | 16777216 | +--------------------+----------+ 1 row in set (0.00 sec) ``` 1 row in set (0.00 sec)
以下是补充内容:
应用程序(如 PHP)长时间执行批量 MySQL 语句,或执行包含 BLOB/longblob 字段(如图片数据处理)的大 SQL 语句,都容易引起 `MySQL server has gone away`。遇到类似情景时,MySQL 会提示此错误。主要原因包括:一是发送的 SQL 语句过长,超过 `max_allowed_packet` 大小,此时需修改 `my.cnf` 加大该值;二是因某些原因导致超时,例如程序采用 Singleton 模式获取数据库连接,虽多次连接但实际复用同一连接,且两次操作间隔超过 `wait_timeout`(可通过 `SHOW STATUS` 查看),此时最简单的处理方式是增大 `wait_timeout`,或在程序中定期调用 `mysql_ping()` 以保持连接活跃。
解决 MySQL server has gone away 错误。
1、应用程序(如 PHP)长时间执行批量 MySQL 语句,常见于数据采集或新旧数据转换场景。
解决方案:
在 `my.cnf` 文件中添加或修改以下两个变量: `wait_timeout=2880000` `interactive_timeout = 2880000` 关于这两个变量的具体说明可参考 Google 搜索结果或官方手册。若无法修改 `my.cnf`,可在连接数据库时设置 `CLIENT_INTERACTIVE`,例如: `sql = "set interactive_timeout=24*3600";` `mysql_real_query(...)`
2、执行单个 SQL 语句,但该语句过大或包含 BLOB/longblob 字段(如图片数据处理)。
解决方案:
在 `my.cnf` 文件中添加或修改以下变量: `max_allowed_packet = 10M`(也可根据需求设置其他大小) `max_allowed_packet` 参数的作用是控制通信缓冲区的最大长度。
最近开发网站时涉及网页采集器功能,当 PHP 脚本请求 URL 时,若目标网页加载极慢,超过了 MySQL 的 `wait-timeout` 时间,待内容抓取完毕准备插入 MySQL 时,会发现连接已超时关闭,从而出现“MySQL server has gone away”错误。基于此经验,提供以下两点解决方法:
第一种方法: 增加 `wait-timeout` 的值。该参数在 `my.cnf`(Windows 下为 `my.ini`)中设置。由于我的数据库负荷稍大,设置为 10(单位秒,表示连接在 10 秒内无操作则强制关闭)。我使用的是 `mysql_connect` 而非永久链接 `mysql_pconnect`。关于 `wait-timeout` 的效果,可通过 `show processlist` 查看。一般建议设置为 300 秒左右,MySQL 默认值为 8 小时,具体可根据服务器和站点情况调整。
第二种方法: 这也是我个人认为较好的方法,即检查 MySQL 链接状态并在必要时重新连接。虽然资料称 `mysql_ping` API 会在断开时尝试重连,但测试发现需通过 C API 的 `mysql_options` 传递参数启用自动重连选项(MySQL 默认不自动重连)。PHP 的 MySQL API 中未直接提供此函数,需重新编译 MySQL。但 `mysql_ping` 仍可使用,只需配合一个小技巧:
这是我的数据库操作类中的一个函数:
```php function ping(){ if(!mysql_ping($this->link)){ mysql_close($this->link); //注意:一定要先执行数据库关闭,这是关键 $this->connect(); } } ``` 我需要调用这个函数的代码可能如下: ```php $str = file_get_contents('//www.jb51.net'); $db->ping();//经过前面的网页抓取后,可能导致数据库连接关闭,检查并重新连接 $db->query('select * from table'); ``` `ping()` 函数先检测数据连接是否正常,若被关闭,则先关闭当前脚本的 MySQL 实例,再重新连接。经此处理后,可有效解决 `MySQL server has gone away` 问题,且不会给系统带来额外开销。
今天遇到类似情景,MySQL 提示:MySQL server has gone away。 大概浏览了一下,主要可能是因为以下几种原因: 一种可能是发送的 SQL 语句太长,以致超过了 max_allowed_packet 的大小,如果是这种原因,你只要修改 my.cnf,加大 max_allowed_packet 的值即可。 还有一种可能是因为某些原因导致超时,比如说程序中获取数据库连接时采用了 Singleton 的做法,虽然多次连接数据库,但其实使用的都是同一个连接,而且程序中某两次操作数据库的间隔时间超过了 wait_timeout(SHOW STATUS 能看到此设置),那么就可能出现问题。最简单的处理方式就是把 wait_timeout 改大,当然你也可以在程序里时不时顺手 mysql_ping() 一下,这样 MySQL 就知道它不是一个人在战斗。 解决 MySQL server has gone away 1、应用程序(比如 PHP)长时间的执行批量的 MYSQL 语句。最常见的就是采集或者新旧数据转化。 解决方案: 在 my.cnf 文件中添加或者修改以下两个变量: wait_timeout=2880000 interactive_timeout = 2880000 关于两个变量的具体说明可以 google 或者看官方手册。如果不能修改 my.cnf,则可以在连接数据库的时候设置 CLIENT_INTERACTIVE,比如: sql = "set interactive_timeout=24*3600"; mysql_real_query(...) 2、执行一个 SQL,但 SQL 语句过大或者语句中含有 BLOB 或者 longblob 字段。比如,图片数据的处理 解决方案: 在 my.cnf 文件中添加或者修改以下变量: max_allowed_packet = 10M (也可以设置自己需要的大小) max_allowed_packet 参数的作用是,用来控制其通信缓冲区的最大长度。 1、应用程序(比如 PHP)长时间的执行批量的 MYSQL 语句。 最常见的就是采集或者新旧数据转化。
解决方案: 在 my.ini 文件中添加或者修改以下两个变量: wait_timeout=2880000 interactive_timeout = 2880000 关于两个变量的具体说明可以 google 或者看官方手册。 如果不能修改 my.cnf,则可以在连接数据库的时候设置 CLIENT_INTERACTIVE,比如: sql = "set interactive_timeout=24*3600"; mysql_real_query(...) 2、执行一个 SQL,但 SQL 语句过大或者语句中含有 BLOB 或者 longblob 字段。 比如,图片数据的处理 解决方案 在 my.cnf 文件中添加或者修改以下变量: max_allowed_packet = 10M (也可以设置自己需要的大小) max_allowed_packet 参数的作用是,用来控制其通信缓冲区的最大长度。
修改方法
1)方法 1 可以编辑 my.cnf 来修改(Windows 下为 my.ini),在 `[mysqld]` 段或者 MySQL 的 server 配置段进行修改。
`max_allowed_packet = 20M` 如果找不到 my.cnf 可以通过
`mysql --help | grep my.cnf` 去寻找 my.cnf 文件。
2)方法 2 (比较妥协且纠结的办法)
进入 MySQL Server
在 MySQL 命令行中运行
`set global max_allowed_packet = 2*1024*1024*10` 然后关闭当前的 MySQL Server 链接,再重新进入。
`show VARIABLES like '%max_allowed_packet%';` 查看下 max_allowed_packet 是否编辑成功 ------------ 以下是网络搜索的资料 -------------------
也许其他人遇到这个问题,不一定是这儿的原因,那么,就把我在网上找到比较全面的分析放到下面: 有两篇,第一篇比较直观,第二篇比较深奥。 解决 MySQL server has gone away 2009-01-09 16:23:22 今天遇到类似的情景,MySQL 只是冷冷的说:MySQL server has gone away。 大概浏览了一下,主要可能是因为以下几种原因: 一种可能是发送的 SQL 语句太长,以致超过了 max_allowed_packet 的大小,如果是这种原因,你只要修改 my.cnf,加大 max_allowed_packet 的值即可。 还有一种可能是因为某些原因导致超时,比如说程序中获取数据库连接时采用了 Singleton 的做法,虽然多次连接数据库,但其实使用的都是同一个连接,而且程序中某两次操作数据库的间隔时间超过了 wait_timeout(SHOW STATUS 能看到此设置),那么就可能出现问题。最简单的处理方式就是把 wait_timeout 改大,当然你也可以在程序里时不时顺手 mysql_ping() 一下,这样 MySQL 就知道它不是一个人在战斗。 解决 MySQL server has gone away 1、应用程序(比如 PHP)长时间的执行批量的 MYSQL 语句。最常见的就是采集或者新旧数据转化。 解决方案: 在 my.cnf 文件中添加或者修改以下两个变量: wait_timeout=2880000 interactive_timeout = 2880000 关于两个变量的具体说明可以 google 或者看官方手册。如果不能修改 my.cnf,则可以在连接数据库的时候设置 CLIENT_INTERACTIVE,比如: sql = "set interactive_timeout=24*3600"; mysql_real_query(...) 2、执行一个 SQL,但 SQL 语句过大或者语句中含有 BLOB 或者 longblob 字段。比如,图片数据的处理 解决方案: 在 my.cnf 文件中添加或者修改以下变量: max_allowed_packet = 10M (也可以设置自己需要的大小) max_allowed_packet 参数的作用是,用来控制其通信缓冲区的最大长度 MySQL: 诡异的 MySQL server has gone away 及其解决 在 Mysql 执行 show status,通常更关注缓存效果、进程数等,往往忽略了两个值: Variable_name Value Aborted_clients 3792 Aborted_connects 376 通常只占 query 的 0.0x%,所以并不为人所重视。而且在传统 Web 应用上,query 错误对用户而言影响并不大,只是重新刷新一下页面就 OK 了。最近的基础改造中,把很多应用作为 service 运行,无法提示用户重新刷新,这种情况下,可能就会影响到服务的品质。 通过程序脚本的日志跟踪,主要报错信息为“MySQL server has gone away”。官方的解释是: The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection. Some other common reasons for the MySQL server has gone away error are: You (or the db administrator) has killed the running thread with a KILL statement or a mysqladmin kill command. You tried to run a query after closing the connection to the server. This indicates a logic error in the application that should be corrected. A client application running on a different host does not have the necessary privileges to connect to the MySQL server from that host. You got a timeout from the TCP/IP connection on the client side. This may happen if you have been using the commands: mysql_options(..., MYSQL_OPT_READ_TIMEOUT,...) or mysql_options(..., MYSQL_OPT_WRITE_TIMEOUT,...). In this case increasing the timeout may help solve the problem. You have encountered a timeout on the server side and the automatic reconnection in the client is disabled (the reconnect flag in the MYSQL structure is equal to 0). You are using a Windows client and the server had dropped the connection (probably because wait_timeout expired) before the command was issued. The problem on Windows is that in some cases MySQL doesn't get an error from the OS when writing to the TCP/IP connection to the server, but instead gets the error when trying to read the answer from the connection. In this case, even if the reconnect flag in the MYSQL structure is equal to 1, MySQL does not automatically reconnect and re-issue the query as it doesn't know if the server did get the original query or not. The solution to this is to either do a mysql_ping on the connection if there has been a long time since the last query (this is what MyODBC does) or set wait_timeout on the mysqld server so high that it in practice never times out. You can also get these errors if you send a query to the server that is incorrect or too large. If mysqld receives a packet that is too large or out of order, it assumes that something has gone wrong with the client and closes the connection. If you need big queries (for example, if you are working with big BLOB columns), you can increase the query limit by setting the server's max_allowed_packet variable, which has a default value of 1MB. You may also need to increase the maximum packet size on the client end. More information on setting the packet size is given in Section A.1.2.9, “Packet too large”. An INSERT or REPLACE statement that inserts a great many rows can also cause these sorts of errors. Either one of these statements sends a single request to the server irrespective of the number of rows to be inserted; thus, you can often avoid the error by reducing the number of rows sent per INSERT or REPLACE. You also get a lost connection if you are sending a packet 16MB or larger if your client is older than 4.0.8 and your server is 4.0.8 and above, or the other way around. It is also possible to see this error if hostname lookups fail (for example, if the DNS server on which your server or network relies goes down). This is because MySQL is dependent on the host system for name resolution, but has no way of knowing whether it is working — from MySQL's point of view the problem is indistinguishable from any other network timeout. You may also see the MySQL server has gone away error if MySQL is started with the --skip-networking option. Another networking issue that can cause this error occurs if the MySQL port (default 3306) is blocked by your firewall, thus preventing any connections at all to the MySQL server. You can also encounter this error with applications that fork child processes, all of which try to use the same connection to the MySQL server. This can be avoided by using a separate connection for each child process. You have encountered a bug where the server died while executing the query. 据此分析,可能原因有 3: 1,Mysql 服务端与客户端版本不匹配。 2,Mysql 服务端配置有缺陷或者优化不足 3,需要改进程序脚本 通过更换多个服务端与客户端版本,发现只能部分减少报错,并不能完全解决。排除 1。 对服务端进行了彻底的优化,也未能达到理想效果。在 timeout 的取值设置上,从经验值的 10,到 PHP 默认的 60,进行了多次尝试。而 Mysql 官方默认值 (8 小时) 明显是不可能的。从而对 2 也进行了排除。(更多优化的经验分享,将在以后整理提供) 针对 3 对程序代码进行分析,发现程序中大量应用了类似如下的代码 (为便于理解,用原始 api 描述): $conn=mysql_connect( ... ... ); ... ... ... ... if(!$conn){ //reconnect $conn=mysql_connect( ... ... ); } mysql_query($sql, $conn); 这段代码的含义,与 Mysql 官方建议的方法思路相符 [ If you have a script, you just have to issue the query again for the client to do an automatic reconnection. ]。在实际分析中发现,if(!$conn) 并不是可靠的,程序通过了 if(!$conn) 的检验后,仍然会返回上述错误。 对程序进行了改写: if(!conn){ // connect ...} elseif(!mysql_ping($conn)){ // reconnect ... } mysql_query($sql, $conn); 经实际观测,MySQL server has gone away 的报错基本解决。 BTW: 附带一个关于 reconnect 的疑问, 在 php4x+client3x+mysql4x 的旧环境下,reconnet 的代码: $conn=mysql_connect(...) 可以正常工作。 但是,在 php5x+client4x+mysql4x 的新环境下,$conn=mysql_connect(...) 返回的$conn 有部分情况下不可用。需要书写为: mysql_close($conn); $conn=mysql_connect(...); 返回的$conn 才可以正常使用。原因未明。未做深入研究,也未见相关讨论。或许 mysql 官方的 BUG 汇报中会有吧。 ~~呵呵~~ 本文来自 CSDN 博客,转载请标明出处:http://blog.csdn.net/brightsnow/archive/2009/03/17/3997705.aspx description: remember that your MySQL "max_allowed_packet" configuration setting (default 1MB) mysql 默认最大能够处理的是 1MB 如果你在 sql 使用了大的 text 或者 BLOB 数据,就会出现这个问题。 php 手册上的注释 When trying to INSERT or UPDATE and trying to put a large amount of text or data (blob) into a mysql table you might run into problems. In mysql.err you might see: Packet too large (73904) To fix you just have to start up mysql with the option -O max_allowed_packet=maxsize You would just replace maxsize with the max size you want to insert, the default is 65536 mysql 手册上说 Both the client and the server have their own max_allowed_packet variable, so if you want to handle big packets, you must increase this variable both in the client and in the server. If you are using the mysql client program, its default max_allowed_packet variable is 16MB. To set a larger value, start mysql like this: shell> mysql --max_allowed_packet=32M That sets the packet size to 32MB. The server's default max_allowed_packet value is 1MB. You can increase this if the server needs to handle big queries (for example, if you are working with big BLOB columns). For example, to set the variable to 16MB, start the server like this: shell> mysqld --max_allowed_packet=16M You can also use an option file to set max_allowed_packet. For example, to set the size for the server to 16MB, add the following lines in an option file: [mysqld]max_allowed_packet=16M 使用 mysql 做数据库还原的时候,由于有些数据很大,会出现这样的错误:The MySQL Server returned this Error:MySQL Error Nr.2006-MySQL server has gone away。我的一个 150mb 的备份还原的时候就出现了这错误。解决的方法就是找到 mysql 安装目录,找到 my.ini 文件,在文件的最后添加:max_allowed_packet = 10M(也可以设置自己需要的大小)。 max_allowed_packet 参数的作用是,用来控制其通信缓冲区的最大长度。