1. 程式人生 > >【MySQL】關於資料庫連線超時

【MySQL】關於資料庫連線超時

最近經常碰到MySQL server has gone awayLost connection during query的問題。不定期發生的問題困擾了我好久。

關於MySQL server has gone away一個原因是由於在規定的時間(time_out)內如果沒有任何操作的話,就會被MySQL強行關閉連線。我檢查了指令碼多出相關連線的地方,發現有些連線開啟後,並沒有直接進行資料的增刪查改,而是現在應用程式裡面做了某些運算後才與資料庫互動。所以,我在只有與資料庫互動的時候才打開資料連線,操作完成後就關閉連線。在沒有頻繁操作資料的情況下,這種方法貌似有效的減少了連線被關閉的次數。

另外一個主要原因可能是sql語句過長,或使MySQL的client和server之間的資料包超過了max_allowed_packet的限制。這種情況可以通過增大max_allowed_packet的值,或者將原來的資料切成多塊分批再進行傳送等方法來解決。

而至於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
The client couldn't send a question to the server.
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.

上面的意思應該是指這兩種報錯的原因是類似的,很可能的原因都是連線超時而被關閉了。

在我的實際生產環境下,有幾次是因為表太大而導致了查詢操作超時。除了修改超時的樹枝,暫時沒有找到好的解決方法,準備嘗試做表的垂直切分,看看效果如何。