diff options
author | Arne Georg Gleditsch <argggh@lxr.linpro.no> | 2008-02-08 01:17:25 +0100 |
---|---|---|
committer | Arne Georg Gleditsch <argggh@lxr.linpro.no> | 2008-02-08 01:17:25 +0100 |
commit | 8038cc1ba3d260ac1017d0ffe2105c29ed716b5f (patch) | |
tree | b9c53777136240dea9b05cf7cc9ca0d57bdb813b /lib/LXRng/Cached.pm | |
parent | 2e28387613b7de506671f1657ed539d2470caff1 (diff) |
Avoid establishing memcached connection at compile time.
Diffstat (limited to 'lib/LXRng/Cached.pm')
-rw-r--r-- | lib/LXRng/Cached.pm | 33 |
1 files changed, 22 insertions, 11 deletions
diff --git a/lib/LXRng/Cached.pm b/lib/LXRng/Cached.pm index 06523bc..e713700 100644 --- a/lib/LXRng/Cached.pm +++ b/lib/LXRng/Cached.pm @@ -23,7 +23,7 @@ use strict; use LXRng; require Exporter; -use vars qw($memcached @ISA @EXPORT); +use vars qw($memcached $has_memcached $nspace @ISA @EXPORT); @ISA = qw(Exporter); @EXPORT = qw(cached); @@ -33,16 +33,27 @@ BEGIN { require Digest::SHA1; }; if ($@ eq '') { - my $nspace = substr(Digest::SHA1::sha1_hex($LXRng::ROOT), 0, 8); - - $memcached = Cache::Memcached->new({ - 'servers' => ['127.0.0.1:11211'], - 'namespace' => 'lxrng:$nspace'}); - $memcached = undef - unless ($memcached->set(':caching' => 1)) + $has_memcached = 1; + $nspace = substr(Digest::SHA1::sha1_hex($LXRng::ROOT), 0, 8); } } +sub handle { + return undef unless $has_memcached; + return $memcached if $memcached; + + $memcached = Cache::Memcached->new({ + 'servers' => ['127.0.0.1:11211'], + 'namespace' => 'lxrng:$nspace'}); + + unless ($memcached->set(':caching' => 1)) { + $memcached = undef; + $has_memcached = undef; + } + return $memcached; +} + + # Caches result from block enclosed by cache { ... }. File/linenumber # of the "cache" keyword is used as the caching key. If additional # arguments are given after the sub to cache, they are used to further @@ -56,7 +67,7 @@ package DB; sub LXRng_Cached_cached(&;@) { my ($func, @args) = @_; - if ($LXRng::Cached::memcached) { + if (LXRng::Cached::handle) { my ($pkg, $file, $line) = caller(0); my $params; unless (@args > 0) { @@ -67,10 +78,10 @@ sub LXRng_Cached_cached(&;@) { $params = Storable::freeze(\@args); my $key = Digest::SHA1::sha1_hex(join("\0", $file, $line, $params)); - my $val = $LXRng::Cached::memcached->get($key); + my $val = LXRng::Cached::handle->get($key); unless ($val) { $val = [$func->()]; - $LXRng::Cached::memcached->set($key, $val, 3600); + LXRng::Cached::handle->set($key, $val, 3600); # warn "cache miss for $key (".join(":", $file, $line, @args).")\n"; } else { |