【发布时间】:2014-11-22 08:52:06
【问题描述】:
当 MySQL 位于应用程序之外的另一台服务器上时,查询速度非常慢。这与预期的延迟(网络瓶颈等)无关;当我使用 Codeigniter 时,我从来没有遇到过这个问题。它看起来也不像是 DNS 问题,而且我在我测试过的每台 vagrant 机器和服务器上都遇到了这个问题。
为了弄清楚发生了什么,我编写了一个简单的测试,运行相同的查询但使用不同的方法:
- PDO 实例是使用 DSN 手动创建的
- PDO 实例由
DB::getPdo()返回 - 查询生成器
测试结果截图:。
这是代码:
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 数据库与应用程序在同一台服务器上时,我没有这些问题。
【问题讨论】: