c mysql 超时_利用mysql c api操作数据库的读/写超时问题

在数据库服务器网络状况不佳时,程序可能会在数据库访问中阻塞。本文介绍了如何通过设置MYSQL_OPT_READ_TIMEOUT和MYSQL_OPT_WRITE_TIMEOUT来解决MySQL C API的读/写超时问题,以及这些选项在不同版本的适用性和限制。对于Linux系统,需要确保使用5.1.12版本后的客户端库。
摘要由CSDN通过智能技术生成

以前开发的程序在数据库服务器发生网络较差的情况下会发生报警处理程序阻塞在对数据库的访问操作上无法继续。

也有同事直接调用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=) 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版本之后的客户端库,否则你需要自己编译线程安全的客户端库。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值