最近经常碰到MySQL server has gone away和Lost connection during query的问题。不定期发生的问题困扰了我好久。
关于MySQL server has gone away,一个原因是由于在规定的时间(time_out)内如果没有任何操作的话,就会被MySQL强行关闭连接。我检查了脚本多出相关连接的地方,发现有些连接打开后,并没有直接进行数据的增删查改,而是现在应用程序里面做了某些运算后才与数据库交互。所以,我在只有与数据库交互的时候才打开数据连接,操作完成后就关闭连接。在没有频繁操作数据的情况下,这种方法貌似有效的减少了连接被关闭的次数。
另外一个主要原因可能是sql语句过长,或使MySQL的client和server之间的数据包超过了max_allowed_packet的限制。这种情况可以通过增大max_allowed_packet的值,或者将原来的数据切成多块分批再进行传送等方法来解决。
(参考上一篇关于查询切分的文章: http://blog.youkuaiyun.com/moxiaomomo/article/details/10307571)
而至于Lost connection during query,在官方文档里似乎没找到详细的解析,但是有这样的描述:
C.5.2.9. MySQL server has gone away
This section also covers the related Lost connection to server during query
error.
The most common reason for the MySQL server has gone away
error is that the server timed out and closed the connection. In this case, you normally get one of the following error codes (which one you get is operating system-dependent).
Error Code | Description |
---|---|
CR_SERVER_GONE_ERROR | The client couldn't send a question to the server. |
CR_SERVER_LOST | The client didn't get an error when writing to the server, but it didn't get a full answer (or any answer) to the question. |
上面的意思应该是指这两种报错的原因是类似的,很可能的原因都是连接超时而被关闭了。
在我的实际生产环境下,有几次是因为表太大而导致了查询操作超时。除了修改超时的树枝,暂时没有找到好的解决方法,准备尝试做表的垂直切分,看看效果如何。