Jul*_*ien 8 perl caching dbix-class
在C#/ .Net世界中,有一些ORM,如NHibernate或ActiveRecord,包括透明缓存:数据库更新透明地复制到缓存,对象在可用时直接从缓存中检索等(通常使用memcached).
在带有DBIx :: Class的 Perl中,它看起来不像透明缓存.我错过了什么?这似乎是一个普遍的需求,我很惊讶我在CPAN或谷歌上找不到任何东西.
半透明地有DBIx :: Class :: Cursor :: Cached(来自mst,如DBIC).您需要为连接或模式对象提供Cache对象.遗憾的是,似乎没有证据.
Cookbook确实有一个在DBIC上使用Tie :: Cache的例子,在DBIx :: Class :: ResultSet上也有(get | set | clear)_cache函数,但它们可能不是你需要的.
这是一种可以使用CHI添加缓存的简单方法.我实际上没有尝试过这个,所以可能有一些我没有考虑过的陷阱,特别是关于DBIC结果集的序列化.
package My::Table;
use strict;
use warnings;
use base 'DBIx::Class';
use Storable 'freeze';
use CHI;
$Storable::canonical = 1;
__PACKAGE__->load_components(qw/Core/);
__PACKAGE__->table('mytable');
# ....
my $CACHE = CHI->new( driver => 'Memory' );
sub search {
my $self = shift;
my $key = freeze( \@_ ); # make cache key from params
if ( my $rs = $CACHE->get( $key ) ) {
return $rs;
}
# Note: there are issues with context propagation here
my $rs = $self->next::method( @_ );
$CACHE->set( $key => $rs );
return $rs;
}
sub update {
my $self = shift;
my @keys = $self->find_all_cache_items_affected_by_this_update( @_ );
$CACHE->remove( $_ ) for @keys;
$self->next::method( @_ );
}
Run Code Online (Sandbox Code Playgroud)
它有点笨重,但我认为这是一个很好的起点.如果在所有DBIx :: Class表类的基类中执行此类操作,则应该能够非常轻松地构建透明缓存.