您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

mysql设置查询超时方法

2024/3/16 8:05:09发布17次查看
文章来介绍了自定义mysql查询超时的时间长度,下面我们来看看详细的设置方法。
首先, 在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秒…
虽说大了点,, 不过总比没有好, 呵呵
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product