博客
关于我
MySQL 异步查询提高查询速度
阅读量:432 次
发布时间:2019-03-05

本文共 1814 字,大约阅读时间需要 6 分钟。

本文解决什么问题

什么是 MySQL 异步查询

MySQL 异步查询的优缺点

一个例子

异步查询功能

MySQLi 扩展提供了异步查询功能,需要使用 mysqlnd ( MySQL Native Driver ) 作为数据库的驱动。

mysqlnd 是 Zend 公司开发的 MySQL 数据库驱动,采用 PHP 开源协议,用于代替旧版的有 MySQL AB 公司(现 oracle) 开发的 libmysql, PHP 5.3 版本之后提供, PHP 5.4 之后的版本 mysqlnd 为默认配置选项。

MySQL 异步查询的优缺点

异步查询会开启多条 MySQL 线程,会带来一定的 cpu占用和内存使用。但是换来的是更高的查询速度。

比如我们 100w 数据在 40 张表中,原先查 40 张表的 union all 视图需要 20 多秒,使用的异步查询基本 1秒不到就出结果了。

一个列子

背景: 查询 40 张分表的数据,性能换时间。

主要使用了 MySQLI 提供的 mysqli_poll、reap_async_query 扩展方法

$table_separate_cnt = 40;      $sqls               = [];      for ( $i = 0; $i < $table_separate_cnt; $i ++ ) {        $sql = 'select * from news' + $i;        array_push( $sqls, $sql );      }      $links = [];      // 链接数据库,并发起异步查询      foreach ( $sqls as $sql ) {        $link = mysqli_connect( $hostname, $username, $password, 'test', '3306' );        $link->query( $sql, MYSQLI_ASYNC ); // 发起异步查询,立即返回        $links[ $link->thread_id ] = $link;      }      $llen    = count( $links );      $process = 0;      $res     = [];      do {        $r_array = $e_array = $reject = $links;        // 多路复用轮询IO        if ( ! ( $ret = mysqli_poll( $r_array, $e_array, $reject, 2 ) ) ) {          continue;        }        // 读取有结果返回的查询,处理结果        foreach ( $r_array as $link ) {          if ( $result = $link->reap_async_query() ) {            $r = $result->fetch_array();            if($r)            {              $res[] = $r;            }            if ( is_object( $result ) ) {              mysqli_free_result( $result );            }          }          // 操作完后,把当前数据链接从待轮询集合中删除          unset( $links[ $link->thread_id ] );          $link->close();          $process ++;        }        foreach ( $e_array as $link ) {          die;        }        foreach ( $reject as $link ) {          die;        }      } while ( $process < $llen );

转载地址:http://enuzz.baihongyu.com/

你可能感兴趣的文章
Neo4j(3):Neo4j Desktop安装
查看>>
Neo4j(4):Neo4j - CQL使用
查看>>
Neo图数据库与python交互
查看>>
NEO改进协议提案1(NEP-1)
查看>>
Neo私链
查看>>
NervanaGPU 项目使用教程
查看>>
Nerves 项目教程
查看>>
nessus快速安装使用指南(非常详细)零基础入门到精通,收藏这一篇就够了
查看>>
Nessus漏洞扫描教程之配置Nessus
查看>>
Nest.js 6.0.0 正式版发布,基于 TypeScript 的 Node.js 框架
查看>>
nested exception is org.apache.ibatis.builder.BuilderException: Error parsing Mapper XML.
查看>>
nestesd exception is java .lang.NoSuchMethodError:com.goolge.common.collect
查看>>
nestJS学习
查看>>
net core 环境部署的坑
查看>>
NET Framework安装失败的麻烦
查看>>
Net 应用程序如何在32位操作系统下申请超过2G的内存
查看>>
Net.Framework概述
查看>>
NET3.0+中使软件发出声音[整理篇]<转>
查看>>
net::err_aborted 错误码 404
查看>>
NetApp凭借领先的混合云数据与服务把握数字化转型机遇
查看>>