| 1 | package Mojolicious::Service::SessionFile; | ||
| 2 | 0 | ▶ | use Mojo::Base 'Mojolicious::Service'; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 3 | |||
| 4 | use Mojo::JSON qw/from_json to_json/; | ||
| 5 | use Mojo::File 'path'; | ||
| 6 | use Encode qw/decode_utf8 encode_utf8/; | ||
| 7 | use Mojo::Cache; | ||
| 8 | |||
| 9 | has path => "session"; | ||
| 10 | has max_cache_keys => 100; | ||
| 11 | has cache => sub{Mojo::Cache->new(max_keys => shift->max_cache_keys)}; | ||
| 12 | |||
| 13 | sub fetch{ | ||
| 14 | my $self = shift; | ||
| 15 | my $session_id = shift; | ||
| 16 | |||
| 17 | # 先从缓存中取 | ||
| 18 | my $session = $self->cache->get($session_id); | ||
| 19 | |||
| 20 | # 缓存中没有,则从session文件中取 | ||
| 21 | unless($session){ | ||
| 22 | my $home = $self->app->home; | ||
| 23 | my $file = $home->child($self->path, $session_id); | ||
| 24 | my $file_content = -e $file ? $file->slurp : undef; | ||
| 25 | if($file_content){ | ||
| 26 | $session = from_json(decode_utf8 $file_content); | ||
| 27 | # 从session文件中取到后需要设置缓存 | ||
| 28 | $self->cache->set($session_id => $session); | ||
| 29 | } | ||
| 30 | } | ||
| 31 | |||
| 32 | if($session){ | ||
| 33 | if($session->{expires} && $session->{expires} > time){ | ||
| 34 | return $session; | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | ## 因为cookie也会过期,所以正常情况下是无法执行到下面的代码的 | ||
| 39 | $self->remove($session_id); | ||
| 40 | |||
| 41 | return undef; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub remove{ | ||
| 45 | my $self = shift; | ||
| 46 | my $session_id = shift; | ||
| 47 | my $home = $self->app->home; | ||
| 48 | $home->child($self->path, $session_id)->remove_tree if(defined $session_id && $session_id ne ""); | ||
| 49 | # 删除session文件后需要删除缓存 | ||
| 50 | $self->cache->set($session_id => undef); | ||
| 51 | } | ||
| 52 | |||
| 53 | sub store{ | ||
| 54 | my $self = shift; | ||
| 55 | my $session_id = shift; | ||
| 56 | my $session = shift; | ||
| 57 | my $home = $self->app->home; | ||
| 58 | $home->child($self->path, $session_id)->spurt(encode_utf8(to_json($session))); | ||
| 59 | # 存储session文件后需要设置缓存 | ||
| 60 | $self->cache->set($session_id => $session); | ||
| 61 | } | ||
| 62 | |||
| 63 | |||
| 64 | |||
| 65 | |||
| 66 | |||
| 67 | |||
| 68 | |||
| 69 | 1; # End of Mojolicious::Sessions::Storage::File | ||