以前开发的程序在数据库服务器发生网络较差的情况下会发生报警处理程序阻塞在对数据库的访问操作上无法继续。
也有同事直接调用mysql客户端时遇到过该问题:用脚本开发的mysql操作数据库过程遇到网络丢包严重的情况也会出现mysql命令卡死无法退出的情况,后来只得另外加一个检视进程查看数据库操作是否超时,如果超时则将其kill掉。
对程序进行调试,发现程序阻塞在从服务端读取结果上:
#0 0x0000003124c0d91b in read () from /lib64/libpthread.so.0
#1 0x0000000000441358 in read (vio=0x2aaaac1f0ca0,
buf=0x2aaaac1f0da0 "183a\f218.61.15.11\n1304402857\n1305519023D", size=16384)
at /usr/include/bits/unistd.h:35
#2 vio_read (vio=0x2aaaac1f0ca0, buf=0x2aaaac1f0da0 "183a\f218.61.15.11\n1304402857\n1305519023D", size=16384)
at viosocket.c:43
#3 0x00000000004413b3 in vio_read_buff (vio=0x2aaaac1f0ca0,
buf=0x2aaaac1f4db9 "2bc1a8ef012e5074e6123a71\f118.180.5.17\n1304402857\n1305519023", size=59)
at viosocket.c:81
#4 0x0000000000442585 in my_real_read (net=0x2aaaac1f07b0, complen=0x43203d50) at net.c:817
#5 0x0000000000442989 in my_net_read (net=0xe) at net.c:991
#6 0x000000000043c452 in cli_safe_read (mysql=0x2aaaac1f07b0) at client.c:603
#7 0x000000000043c9f4 in cli_read_rows (mysql=0x2aaaac1f07b0, mysql_fields=0x2aaaac1fae70, fields=4)
at client.c:1389
#8 0x000000000043c31e in mysql_store_result (mysql=<value optimized out>) at client.c:2817
数据库读/写超时可以通过调用mysql_options()设置,具体参数为MYSQL_OPT_READ_TIMEOUT和MYSQL_OPT_WRITE_TIMEOUT。
MYSQL_OPT_READ_TIMEOUT (argument type: unsigned int *)
The timeout in seconds for attempts to read from the server. Each attempt uses this timeout value and there are retries if necessary, so the total effective timeout value is three times the option value. You can set the value so that a lost connection can be detected earlier than the TCP/IP Close_Wait_Timeout value of 10 minutes. Before MySQL 5.1.41, this option applies only to TCP/IP connections and, prior to MySQL 5.1.12, only for Windows.
MYSQL_OPT_WRITE_TIMEOUT (argument type: unsigned int *)
The timeout in seconds for attempts to write to the server. Each attempt uses this timeout value and there are net_retry_count retries if necessary, so the total effective timeout value is net_retry_count times the option value. Before MySQL 5.1.41, this option applies only to TCP/IP connections and, prior to MySQL 5.1.12, only for Windows.
然而,值得注意的是此两个参数并不是对所有版本都支持:
Before MySQL 5.1.41, this option applies only to TCP/IP connections and, prior to MySQL 5.1.12, only for Windows.
对于linux系统来说,你必须使用官方发布的5.1.12版本之后的客户端库,否则你需要自己编译线程安全的客户端库。
--转自