DBI语句可以处理使用缓存调用execute()吗?

时间:2011-09-30 10:01:58

标签: performance perl dbi

我有一个应用程序,其中数据库很少更改,并且应用程序需要从数据库中进行许多读取,这会显着降低性能。其中许多读取完全相同。所以我想让DBI缓存数据库读取的结果。

例如,

$sth = $dbh->prepare('SELECT a, b FROM a_table WHERE c = ?');
$sth->execute(5);
$sth->execute(2);
$sth->execute(5); # this call loads the cached result set

我首先认为这是prepare_cached所做的,但我意识到它只缓存语句句柄本身,而不是语句句柄的实际执行。

我想我可以通过在memoized sub中包装语句执行来实现我想要的。但我只是看看DBI本身是否有快捷方式。

1 个答案:

答案 0 :(得分:7)

正如你所说,prepare_cached与语句句柄有关,你需要缓存执行的结果。 Memoize很好,但可能需要不时地使缓存无效,并重新执行查询以从数据库获取新的副本。 我使用Cache(http://search.cpan.org/perldoc?Cache)模块。我刚从介绍中复制了这个片段:

use Cache::File;

my $cache = Cache::File->new( cache_root => '/tmp/cacheroot' );
my $customer = $cache->get( $name );

unless ($customer) {
   $customer = get_customer_from_db( $name );
   $cache->set( $name, $customer, '10 minutes' );
}

return $customer;

您可以在内存缓存中使用而不是使用File。此示例使用缓存中的$ customer值(如果存在)且有效,否则获取新值并存储在缓存中(使用10分钟)。

希望这有帮助。