| 1 | package Service::Engine::Data::Redis; | ||
| 2 | |||
| 3 | use 5.010; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Data::Dumper; | ||
| 7 | |||
| 8 | use Service::Engine; | ||
| 9 | use RedisDB; | ||
| 10 | |||
| 11 | our $Config; | ||
| 12 | our $Log; | ||
| 13 | |||
| 14 | sub new { | ||
| 15 | |||
| 16 | my ($class,$options) = @_; | ||
| 17 | |||
| 18 | # set some defaults | ||
| 19 | my $attributes = {'handle'=>''}; | ||
| 20 | |||
| 21 | # load options | ||
| 22 | if (ref($options) eq 'HASH') { | ||
| 23 | foreach my $option (keys %{$options}) { | ||
| 24 | $attributes->{$option} = $options->{$option}; | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 28 | # pull in some Service::Engine globals | ||
| 29 | $Config = $Service::Engine::Config; | ||
| 30 | $Log = $Service::Engine::Log; | ||
| 31 | |||
| 32 | # set some defaults | ||
| 33 | $attributes->{'raise_error'} ||= 0; | ||
| 34 | $attributes->{'port'} ||= 3306; | ||
| 35 | $attributes->{'timeout'} ||= 2; | ||
| 36 | |||
| 37 | if (!$attributes->{'hostname'}) { | ||
| 38 | $Log->log({msg=>"redis requires a hostname",level=>1}); | ||
| 39 | } else { | ||
| 40 | my $handle = eval{RedisDB->new(host => $attributes->{'hostname'}, port => $attributes->{'port'}, password=> $attributes->{'password'}, raise_error => $attributes->{'raise_error'}, timeout => $attributes->{'timeout'});}; | ||
| 41 | if ($@) { | ||
| 42 | $Log->log({msg=>"error connecting to Redis: $@",level=>1}); | ||
| 43 | } else { | ||
| 44 | $attributes->{'handle'} = $handle; | ||
| 45 | } | ||
| 46 | } | ||
| 47 | |||
| 48 | my $self = bless $attributes, $class; | ||
| 49 | |||
| 50 | return $self; | ||
| 51 | |||
| 52 | } | ||
| 53 | |||
| 54 | sub handle { | ||
| 55 | my ($self) = @_; | ||
| 56 | return $self->{'handle'}; | ||
| 57 | } | ||
| 58 | |||
| 59 | sub reconnect { | ||
| 60 | my ($self) = @_; | ||
| 61 | my $handle = eval{RedisDB->new(host => $self->{'hostname'}, port => $self->{'port'}, password=> $self->{'password'}, raise_error => $self->{'raise_error'}, timeout => $self->{'timeout'});}; | ||
| 62 | if ($@) { | ||
| 63 | $Log->log({msg=>"error connecting to Redis: $@",level=>1}); | ||
| 64 | } else { | ||
| 65 | $self->{'handle'} = $handle; | ||
| 66 | } | ||
| 67 | return $self->{'handle'}; | ||
| 68 | } | ||
| 69 | |||
| 70 | 1; |