Skip to content

Instantly share code, notes, and snippets.

@akzhan
Last active April 18, 2017 09:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akzhan/8a4cb983940304271281a1b719f24adb to your computer and use it in GitHub Desktop.
Save akzhan/8a4cb983940304271281a1b719f24adb to your computer and use it in GitHub Desktop.
Simple Redis client module
package YourCompany::Util::Redis;
use YourCompany::Perl;
use YourCompany::Config ();
BEGIN {
require parent;
eval {
parent->import( 'Redis::Fast' );
1;
} or do {
parent->import( 'Redis' );
};
}
my $config = YourCompany::Config->redis;
sub new {
my ( $class ) = @_;
my $index = $config->{index} // 0;
my $self = $class->SUPER::new(
server => "$config->{host}:$config->{port}",
reconnect => 1,
on_connect => sub {
my $self = shift;
$self->select( $index ) if $index != 0;
$self;
},
);
$self;
}
my ( $work_pid, $instance ) = ( 0, undef );
sub instance {
my ( $class ) = @_;
my $pid = $$;
if ( $work_pid != $pid ) {
$instance = undef;
$work_pid = $pid;
}
$instance //= $class->new;
return $instance;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment