【问题标题】:Laravel 4.2: Slow queries when using an external MySQL serverLaravel 4.2:使用外部 MySQL 服务器时查询速度慢
【发布时间】:2014-11-22 08:52:06
【问题描述】:

当 MySQL 位于应用程序之外的另一台服务器上时,查询速度非常慢。这与预期的延迟(网络瓶颈等)无关;当我使用 Codeigniter 时,我从来没有遇到过这个问题。它看起来也不像是 DNS 问题,而且我在我测试过的每台 vagrant 机器和服务器上都遇到了这个问题。

为了弄清楚发生了什么,我编写了一个简单的测试,运行相同的查询但使用不同的方法:

  1. PDO 实例是使用 DSN 手动创建的
  2. PDO 实例由DB::getPdo() 返回
  3. 查询生成器

测试结果截图:。

这是代码:

Route::get('/test', function(){


    $num_queries = 10;


    // manually creating a PDO instance with DSN
    Debugbar::measure('$dbh = new PDO("mysql:host=$hostname;port=$port;dbname=$db", $username, $password)', function() use ($num_queries){

        $hostname = Config::get('database.connections.mysql.host');
        $port = Config::get('database.connections.mysql.port');
        $db = Config::get('database.connections.mysql.database');
        $username = Config::get('database.connections.mysql.username');
        $password = Config::get('database.connections.mysql.password');

        $dbh = new PDO("mysql:host=$hostname;port=$port;dbname=$db", $username, $password);

        for($i = 1; $i <= $num_queries; $i++)
        {
            $sth = $dbh->prepare("SELECT * FROM users WHERE id = ?");
            $sth->execute(array($i));
            $sth->fetch(PDO::FETCH_ASSOC);
        }
    });


    // using DB::getPdo()
    Debugbar::measure('$dbh = DB::getPdo();', function() use ($num_queries){

        $dbh = DB::getPdo();

        for($i = 1; $i <= $num_queries; $i++)
        {
            $sth = $dbh->prepare("SELECT * FROM users WHERE id = ?");
            $sth->execute(array($i));
            $sth->fetch(PDO::FETCH_ASSOC);
        }
    });


    // using the query builder
    Debugbar::measure('Query builder', function() use ($num_queries){

        for($i = 1; $i <= $num_queries; $i++)
        {
            DB::table('users')->where('id', $i)->get();
        }
    });

    return "<h1>$num_queries ".($num_queries == 1 ? 'query' : 'queries')."</h1>";
});

注意DB::getPdo() 在多个查询中的扩展性有多差。其他人经历过这个吗?这里发生了什么?我应该指出,当 MySQL 数据库与应用程序在同一台服务器上时,我没有这些问题。

【问题讨论】:

    标签: php mysql laravel pdo


    【解决方案1】:

    静态调用使用相同的 PDO 实例,因此每次在后台使用相同的实际数据库连接。

    其他人每次都会创建一个新连接,并涉及相关的开销。

    查询速度慢是由于其他原因(可能是生产中的索引 - 使用 EXPLAIN 调试查询)。

    这些调试测试让你走错了路。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-20
      • 2016-06-08
      • 1970-01-01
      • 2014-10-28
      • 2015-03-22
      相关资源
      最近更新 更多