CHI
view release on metacpan or search on metacpan
my $cache = CHI->new( driver => 'DBI',
dbh => $dbh
);
my $cache = CHI->new( driver => 'BerkeleyDB',
root_dir => '/path/to/root'
);
# Create your own driver
#
my $cache = CHI->new( driver => '+My::Special::Driver', ... );
# Cache operations
#
my $customer = $cache->get($name);
if ( !defined $customer ) {
$customer = get_customer_from_db($name);
$cache->set( $name, $customer, "10 minutes" );
}
my $customer2 = $cache->compute($name2, "10 minutes", sub {
get_customer_from_db($name2)
});
$cache->remove($name);
=head1 DESCRIPTION
CHI provides a unified caching API, designed to assist a developer in
persisting data for a specified period of time.
The CHI interface is implemented by driver classes that support fetching,
storing and clearing of data. Driver classes exist or will exist for the gamut
of storage backends available to Perl, such as memory, plain files, memory
mapped files, memcached, and DBI.
CHI is intended as an evolution of DeWitt Clinton's
L<Cache::Cache|Cache::Cache> package, adhering to the basic Cache API but
adding new features and addressing limitations in the Cache::Cache
implementation.
=head1 FEATURES
=over
=item *
Easy to create new drivers
=item *
Uniform support for namespaces
=item *
Automatic serialization of keys and values
=item *
Multilevel caches
=item *
Probabilistic expiration and busy locks, to reduce cache miss stampedes
=item *
Optional logging and statistics collection of cache activity
=back
=for readme stop
=head1 CONSTRUCTOR
To create a new cache object, call C<CHI-E<gt>new>. It takes the common
options listed below. I<driver> is required; all others are optional.
Some drivers will take additional constructor options. For example, the File
driver takes C<root_dir> and C<depth> options.
You can configure default options for each new cache object created - see
L</SUBCLASSING AND CONFIGURING CHI>.
Note that C<CHI-E<gt>new> returns an instance of a subclass of
L<CHI::Driver|CHI::Driver>, not C<CHI>.
=over
=item compress_threshold [INT]
A value in bytes. Automatically compress values larger than this before
storing. Requires L<Compress::Zlib|Compress::Zlib> to be installed. Defaults
to undef, meaning no automatic compression. Inspired by the parameter of the
same name in L<Cache::Memcached>.
# Compress values larger than 1MB
compress_threshold => 1024*1024
=item driver [STRING]
Required. The name of a cache driver, for example "Memory" or "File". CHI will
prefix the string with "CHI::Driver::", unless it begins with '+'. e.g.
driver => 'File'; # uses CHI::Driver::File
driver => '+My::CHI::Driver::File' # uses My::CHI::Driver::File
=item expires_in [DURATION], expires_at [INT], expires_variance [FLOAT]
Provide default values for the corresponding L</set> options.
=item expires_on_backend [NUM]
If set to 0 (the default), CHI alone is aware of the expiration time and does
not pass it along to the backend driver. This allows you to use L</get_object>
to retrieve expired items.
If set to 1, pass expiration times to backend driver if the driver supports it
-- for example, L<CHI::Driver::Memcached|Memcached> and
L<CHI::Driver::CacheCache|CacheCache>. This may allow the driver to better
manage its space and evict items. Note that only simple expiration time will be
passed along, e.g. not L</expires_variance>.
If set to a number greater than 1 (e.g. 1.25), the time until expiration will
created, with the string passed as the 'serializer' option and raw=1. Common
options include 'Storable', 'Data::Dumper', and 'YAML'. If this is a hashref,
L<Data::Serializer-E<gt>new|Data::Serializer> will be called with the hash. You
will need to ensure Data::Serializer is installed to use these options.
Otherwise, this must be a L<Data::Serializer|Data::Serializer> object or
another object that implements I<serialize()> and I<deserialize()>.
e.g.
# Serialize using raw Data::Dumper
my $cache = CHI->new(serializer => 'Data::Dumper');
# Serialize using Data::Dumper, compressed and (per Data::Serializer defaults) hex-encoded
my $cache = CHI->new(serializer => { serializer => 'Data::Dumper', compress => 1 });
# Serialize using custom object
my $cache = CHI->new(serializer => My::Custom::Serializer->new())
The default is to use raw Storable.
=item traits [LISTREF]
List of one or more roles to apply to the C<CHI::Driver> class that is
constructed. The roles will automatically be prefixed with
C<CHI::Driver::Role::> unless preceded with a '+'. e.g.
traits => ['StoresAccessedAt', '+My::CHI::Driver::Role']
=back
=head1 INSTANCE METHODS
The following methods can be called on any cache handle returned from
CHI-E<gt>new(). They are implemented in the L<CHI::Driver|CHI::Driver> package.
=head2 Getting and setting
=over
=item get( $key, [option =E<gt> value, ...] )
Returns the data associated with I<$key>. If I<$key> does not exist or has
expired, returns undef. Expired items are not automatically removed and may be
examined with L</get_object> or L</get_expires_at>.
I<$key> may be followed by one or more name/value parameters:
=over
=item expire_if [CODEREF]
If I<$key> exists and has not expired, call code reference with the
L<CHI::CacheObject|CHI::CacheObject> and L<CHI::Driver|CHI::Driver> as the
parameters. If code returns a true value, C<get> returns undef as if the item
were expired. For example, to treat the cache as expired if I<$file> has
changed since the value was computed:
$cache->get('foo', expire_if => sub { $_[0]->created_at < (stat($file))[9] });
=item busy_lock [DURATION]
If the value has expired, the get will still return undef, but the expiration
time of the cache entry will be set to the current time plus the specified
L<duration|/DURATION EXPRESSIONS>. This is used to prevent multiple processes
from recomputing the same expensive value simultaneously. The problem with this
technique is that it doubles the number of writes performed - see
L</expires_variance> for another technique.
=item obj_ref [SCALARREF]
If the item exists in cache (even if expired), place the
L<CHI::CacheObject|CHI::CacheObject> object in the provided SCALARREF.
=back
=item set( $key, $data, [$expires_in | "now" | "never" | options] )
Associates I<$data> with I<$key> in the cache, overwriting any existing entry.
Returns I<$data>.
The third argument to C<set> is optional, and may be either a scalar or a hash
reference. If it is a scalar, it may be the string "now", the string "never",
or else a duration treated as an I<expires_in> value described below. If it is
a hash reference, it may contain one or more of the following options. Most of
these options can be provided with defaults in the cache constructor.
=over
=item expires_in [DURATION]
Amount of time from now until this data expires. I<DURATION> may be an integer
number of seconds or a L<duration expression|/DURATION EXPRESSIONS>.
=item expires_at [INT]
The epoch time at which the data expires.
=item expires_variance [FLOAT]
Controls the variable expiration feature, which allows items to expire a little
earlier than the stated expiration time to help prevent cache miss stampedes.
Value is between 0.0 and 1.0, with 0.0 meaning that items expire exactly when
specified (feature is disabled), and 1.0 meaning that items might expire
anytime from now until the stated expiration time. The default is 0.0. A
setting of 0.10 to 0.25 would introduce a small amount of variation without
interfering too much with intended expiration times.
The probability of expiration increases as a function of how far along we are
in the potential expiration window, with the probability being near 0 at the
beginning of the window and approaching 1 at the end.
For example, in all of the following cases, an item might be considered expired
any time between 15 and 20 minutes, with about a 20% chance at 16 minutes, a
40% chance at 17 minutes, and a 100% chance at 20 minutes.
my $cache = CHI->new ( ..., expires_variance => 0.25, ... );
$cache->set($key, $value, '20 min');
$cache->set($key, $value, { expires_at => time() + 20*60 });
( run in 3.031 seconds using v1.01-cache-2.11-cpan-0bb4e1dffa6 )