Skip to content

Commit

Permalink
Add on_connect callback to Redis constructor
Browse files Browse the repository at this point in the history
The on_connect callback will be called after each successful connection.

Signed-off-by: Pedro Melo <melo@simplicidade.org>
  • Loading branch information
melo committed Nov 8, 2012
1 parent fc05c0f commit 70adaa4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/Redis.pm
Expand Up @@ -45,6 +45,7 @@ sub new {
}

$self->{password} = $args{password} if $args{password};
$self->{on_connect} = $args{on_connect} if $args{on_connect};

if ($args{sock}) {
$self->{server} = $args{sock};
Expand Down Expand Up @@ -431,6 +432,8 @@ sub __build_sock {
};
}

$self->{on_connect}->($self) if exists $self->{on_connect};

return;
}

Expand Down Expand Up @@ -807,6 +810,7 @@ back without utf-8 flag turned on.
my $r = Redis->new( sock => '/path/to/sock' );
my $r = Redis->new( reconnect => 60, every => 5000 );
my $r = Redis->new( password => 'boo' );
my $r = Redis->new( on_connect => sub { my ($redis) = @_; ... } );
The C<< server >> parameter specifies the Redis server we should connect
to, via TCP. Use the 'IP:PORT' format. If no C<< server >> option is
Expand Down Expand Up @@ -865,6 +869,11 @@ start or when reconnecting), the Redis C<< AUTH >> command will be send
to the server. If the password is wrong, an exception will be thrown and
reconnect will be disabled.
You can also provide a code reference that will be immediatly after each
sucessfull connection. The C<< on_connect >> attribute is used to
provide the code reference, and it will be called with the first
parameter being the Redis object.
The C<< debug >> parameter enables debug information to STDERR,
including all interactions with the server. You can also enable debug
with the C<REDIS_DEBUG> environment variable.
Expand Down
33 changes: 33 additions & 0 deletions t/06-on-connect.t
@@ -0,0 +1,33 @@
#!perl

use warnings;
use strict;
use Test::More;
use Test::Fatal;
use Redis;
use lib 't/tlib';
use Test::SpawnRedisServer;

my ($c, $srv) = redis(timeout => 1);
END { $c->() if $c }

subtest 'on_connect' => sub {
my $r;
ok($r = Redis->new(server => $srv, on_connect => sub { shift->incr('on_connect') }),
'connected to our test redis-server');
is($r->get('on_connect'), 1, '... on_connect code was run');

ok($r = Redis->new(server => $srv, on_connect => sub { shift->incr('on_connect') }),
'new connection is up and running');
is($r->get('on_connect'), 2, '... on_connect code was run again');

ok($r = Redis->new(reconnect => 1, server => $srv, on_connect => sub { shift->incr('on_connect') }),
'new connection with reconnect enabled');
is($r->get('on_connect'), 3, '... on_connect code one again perfect');

$r->quit;
is($r->get('on_connect'), 4, '... on_connect code works after reconnect also');
};


done_testing();

0 comments on commit 70adaa4

Please sign in to comment.