| 1 | package Mojo::Weixin::Cache; | ||
| 2 | sub new{ | ||
| 3 | return bless {} | ||
| 4 | } | ||
| 5 | sub all { | ||
| 6 | my $self = shift; | ||
| 7 | my @res; | ||
| 8 | for (keys %$self){ | ||
| 9 | if($self->{$_}{ctime}+$self->{$_}{ttl} <= time){push @res,{key=>$_,data=>$self->{$_}{data}}} | ||
| 10 | else{$self->delete($_)} | ||
| 11 | } | ||
| 12 | return wantarray?@res:\@res; | ||
| 13 | } | ||
| 14 | sub count { | ||
| 15 | my $self = shift; | ||
| 16 | my $count = 0; | ||
| 17 | for (keys %$self){ | ||
| 18 | if($self->{$_}{ctime}+$self->{$_}{ttl} <= time){$count++} | ||
| 19 | else{$self->delete($_)} | ||
| 20 | } | ||
| 21 | return $count; | ||
| 22 | } | ||
| 23 | sub store { | ||
| 24 | my $self= shift; | ||
| 25 | my ($data_key,$data,$ttl) = @_; | ||
| 26 | $self->{$data_key}{data} = $data; | ||
| 27 | $self->{$data_key}{ttl} = $ttl; | ||
| 28 | $self->{$data_key}{ctime} = time; | ||
| 29 | |||
| 30 | } | ||
| 31 | sub delete { | ||
| 32 | my $self= shift; | ||
| 33 | my $data_key = shift; | ||
| 34 | delete $self->{$data_key}; | ||
| 35 | } | ||
| 36 | sub retrieve{ | ||
| 37 | my $self = shift; | ||
| 38 | my $data_key = shift; | ||
| 39 | if(exists $self->{$data_key} ){ | ||
| 40 | if(defined $self->{$data_key}{ttl}){ | ||
| 41 | if($self->{$data_key}{ttl} + $self->{$data_key}{ctime} > time){ | ||
| 42 | return $self->{$data_key}{data}; | ||
| 43 | } | ||
| 44 | else{delete $self->{$data_key};return undef} | ||
| 45 | } | ||
| 46 | else{ | ||
| 47 | return $self->{$data_key}{data}; | ||
| 48 | } | ||
| 49 | } | ||
| 50 | else{return undef} | ||
| 51 | } | ||
| 52 | 1; |