Mysql的timeout 以及 python重连
一. 问题
近期使用多线程对数据库操作报错:
(2013, 'Lost connection to MySQL server during query')
二. 解决方案
1. 更改timeout参数
出现这个问题顺便就了解了一下mysql中的timeout都有什么:
mysql> show variables like '%timeout%';
+-----------------------------+----------+
| Variable_name | Value |
+-----------------------------+----------+
| connect_timeout | 10 |
| delayed_insert_timeout | 300 |
| have_statement_timeout | YES |
| innodb_flush_log_at_timeout | 1 |
| 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 |
| rpl_stop_slave_timeout | 31536000 |
| slave_net_timeout | 60 |
| wait_timeout | 28800 |
+-----------------------------+----------+
13 rows in set (0.06 sec)
很多参数,网上对于connection lost这个问题有说改wait_timout也有说net_read_timeout和net_write_timeout的。
那么他们之间到底有什么区别呢?
简单来说:
-
wait_timeout代表的是前一个sql操作和下一个sql操作的间隔。
-
net_read_timeout和net_write_timeout涉及到网络传输中的包的问题。通常情况下,一个sql语句由多个包组成。客户端将一个一个包传给服务端,然后在服务端再将包组合起来变为sql语句执行。如果网络情况太差,导致包迟迟不全,无法组成一个完整的可执行语句,mysql服务端就会放弃这个语句的执行。而这个等待时间就是net_read/write_timeout。
read是服务器从客户端读取;write是服务器向客户端写。
这两个参数都是session level的,可以在每次连接的时候对其进行更改。
此外,需要注意的是,如果问题出在传输执行一个sql的过程中时,使用ping是无法解决的。Mysql协议不允许客户端在一次性数据没有传输完毕的时候,向服务器传输其他的请求。(python里面的处理就是,如果使用了ping就自动断开了本次的执行操作)
This for example typical cause of aborted connections while using Sphinx with large data sets and large buffers. While indexing Sphinx performs sorts and flushes buffers to the disk every so often which can take long enough to trigger default net_write_timeout on the server side.
You could ask why server does not do any flow control and can’t find out client just is just busy and it is not network issue – well this comes from simplicity of MySQL protocol which does not allow client to talk to the server until full result set is fetched. This is also the reason why you can’t stop fetching for ordinary statements and mysql_free_result will have to complete the fetch internally.
Is there any way to tell the server you need more time besides increasing net_write_timeout ? Not what I know of. You can’t use something like mysql_ping because connection is in the stage of getting the data. You can’t even fetch couple of rows every few seconds to show you’re fetching data because there is buffering happening inside MySQL client library so you never know when real network read will happen.
具体改什么还要视自己的情况而定:
详细的net write timeout和wait timeout的比较
2. 测试连接,并将断开的连接重新连接
还有另一个办法,python使用ping()方法测试连接。
但是要注意ping方法不能在使用流式游标进行迭代获取数据的过程中用,否则会报错:
UserWarning: Previous unbuffered result was left incomplete warnings.warn("Previous unbuffered result was left incomplete")
ping()应用于两个sql语句执行之间进行查询,这个检查是为了应付由于超出wait_timeout(而非net_read/write_timeout)服务器自动断开链接的。