您好,欢迎访问一九零五行业门户网

为MySQL设置查询超时_MySQL

bitscn.com
mysql是否可以设置读写超时(非连接超时), 如果可以就可以避免一条sql执行过慢, 导致php超时错误. 这个, 其实可以有. 只不过稍微要麻烦点.
首先, 在libmysql中, 是提供了mysql_opt_read_timeout设置项的, 并且libmysql中提供了设置相关设置项的api, mysql_options:
int stdcall
mysql_options(mysql *mysql,enum mysql_option option, const void *arg)
{
dbug_enter(mysql_option);
dbug_print(enter,(option: %d,(int) option));
switch (option) {
case mysql_opt_connect_timeout:
mysql->options.connect_timeout= *(uint*) arg;
break;
/** 读超时时间 */
case mysql_opt_read_timeout:
mysql->options.read_timeout= *(uint*) arg;
break;
case mysql_opt_write_timeout:
mysql->options.write_timeout= *(uint*) arg;
break;
case mysql_opt_compress:
mysql->options.compress= 1;
/* 以下省略 */
但是, 可惜的是, 目前只有mysqli扩展, 把mysql_options完全暴露给了php:
php_function(mysqli_options)
{
/** 有省略 */
switch (z_type_pp(mysql_value)) {
/** 没有任何限制, 直接传递给mysql_options */
case is_string:
ret = mysql_options(mysql->mysql, mysql_option, z_strval_pp(mysql_value));
break;
default:
convert_to_long_ex(mysql_value);
l_value = z_lval_pp(mysql_value);
ret = mysql_options(mysql->mysql, mysql_option, (char *)&l_value);
break;
}
return_bool(!ret);
}
但是因为mysqli并没有导出这个常量, 所以我们需要通过查看mysql的代码, 得到mysql_opt_read_timeout的实际值, 然后直接调用mysql_options:
enum mysql_option
{
mysql_opt_connect_timeout, mysql_opt_compress, mysql_opt_named_pipe,
mysql_init_command, mysql_read_default_file, mysql_read_default_group,
mysql_set_charset_dir, mysql_set_charset_name, mysql_opt_local_infile,
mysql_opt_protocol, mysql_shared_memory_base_name, mysql_opt_read_timeout,
mysql_opt_write_timeout, mysql_opt_use_result,
mysql_opt_use_remote_connection, mysql_opt_use_embedded_connection,
mysql_opt_guess_connection, mysql_set_client_ip, mysql_secure_auth,
mysql_report_data_truncation, mysql_opt_reconnect,
mysql_opt_ssl_verify_server_cert
};
可以看到, mysql_opt_read_timeout为11.
现在, 我们就可以设置查询超时了:
options(11 /*mysql_opt_read_timeout*/, 1);
$mysql->real_connect(***);
不过, 因为在libmysql中有重试机制(尝试一次, 重试俩次), 所以, 最终我们设置的超时阈值都会三倍于我们设置的值.
也就是说, 如果我们设置了mysql_opt_read_timeout为1, 最终会在3s以后超时结束. 也就是说, 我们目前能设置的最短超时时, 就是3秒…
虽说大了点,, 不过总比没有好, 呵呵
bitscn.com
其它类似信息

推荐信息