在日常开发过程中,为了解决Mysql has gone away问题使用了函数mysql_ping进行数据库的重连,不过在使用中发现mysql_ping有可能会永远阻塞,测试如下:
首先建立好数据库连接,然后sleep(20),在20秒内添加iptables规则,如下:
iptables -A INPUT -p tcp --dport 3306 -jDROP
20秒后使用mysql_ping测试连接,发现会阻塞再mysql_ping,函数调用栈如下:
(gdb) bt
#0 0x00a70402 in __kernel_vsyscall ()
#1 0x00da2b8b in read () from/lib/libpthread.so.0
#2 0x00157238 in vio_read (vio=0x9c21600, buf=0x9c22260 "\a",size=16384) at viosocket.c:47
#3 0x001572ae in vio_read_buff (vio=0x9c21600, buf=0x9c26268"\001", size=4) at viosocket.c:86
#4 0x00157cd5 in my_real_read (net=0x9c21e98, complen=0xbffc30e8) atnet.c:816
#5 0x00158000 in my_net_read (net=0x9c21e98) at net.c:1011
#6 0x001526c8 in cli_safe_read (mysql=0x9c21e98) at client.c:693
#7 0x00154d15 in cli_advanced_command (mysql=0x9c21e98, command=, header=0x0, header_length=0, arg=0x0, arg_length=0,skip_check=0 '\000', stmt=0x0)
at client.c:826
#8 0x001249ce in mysql_ping (mysql=0x9c21e98) at libmysql.c:1421
Strace如下:
[pid 2669] clock_gettime(CLOCK_REALTIME, {1376018916, 45318843}) = 0
[pid 2669] futex(0x87ae0c8, FUTEX_WAIT_PRIVATE, 5, {9, 954681157}
[pid 2658] <... restart_syscall resumed> ) = 0
[pid 2658] write(1, "aaaaaaaaaaaaaaaaaaaaaaa\n", 24) = 24
[pid 2658] write(1, "connection_is_available---1\n", 28) = 28
[pid 2658] write(1, "connection_ping--->\n", 20) = 20
[pid 2658] poll([{fd=3, events=POLLIN|POLLPRI}], 1, 0) = 0 (Timeout)
[pid 2658] write(3, "\1\0\0\0\16", 5) = 5
[pid 2658] read(3,
[pid 2669] <... futex resumed> ) = -1 ETIMEDOUT (Connectiontimed out)
[pid 2669] futex(0x87ae0ac, FUTEX_WAIT_PRIVATE, 2, NULL
将iptables规则删除iptables -D INPUT -p tcp --dport 3306 -j DROP,在一段时间(几秒不定)mysql_ping返回。
可以通过设置读取超时来解决。
int time_out = 1;
mysql_options(mysql,MYSQL_OPT_READ_TIMEOUT,(const char*)&time_out);
//There areretries if necessary, so the total effective timeout value is three times theoption value.
测试设置读超时对查询的影响,如果查询sql时间比较长,会出现Lost connection to MySQL server during query错误。
目前解决使用设置超时解决,但是这样会影响到查询,如果哪位大侠有好的解决方式请赐教,非常感谢。