From 0d6dee4478f1ea28d36281cfa2d542a123a6654b Mon Sep 17 00:00:00 2001 From: Nate Jones Date: Tue, 23 Mar 2010 18:24:10 +0100 Subject: [PATCH] reconnect to redis if the connection went away --- lib/Redis.pm | 12 +++++++++++- t/01-Redis.t | 13 ++++++++++++- t/20-Redis-Hash.t | 6 +++--- 3 files changed, 26 insertions(+), 5 deletions(-) diff --git a/lib/Redis.pm b/lib/Redis.pm index 55fd1a1..e267ec4 100644 --- a/lib/Redis.pm +++ b/lib/Redis.pm @@ -117,7 +117,17 @@ sub AUTOLOAD { return 1; } - my $result = <$sock> || die "can't read socket: $!"; + my $result = <$sock>; + if ( !$result ) { + $self->{sock} = $sock = IO::Socket::INET->new( + PeerAddr => $self->{server}, + Proto => 'tcp', + ) || die $!; + + print $sock $send; + + $result = <$sock> || die "can't read socket: $!"; + } Encode::_utf8_on($result); warn "<< $result" if $self->{debug}; my $type = substr($result,0,1); diff --git a/t/01-Redis.t b/t/01-Redis.t index 756135a..1d596da 100755 --- a/t/01-Redis.t +++ b/t/01-Redis.t @@ -3,7 +3,7 @@ use warnings; use strict; -use Test::More tests => 110; +use Test::More tests => 111; use Data::Dumper; use lib 'lib'; @@ -26,6 +26,17 @@ ok( ! $o->setnx( foo => 'bar' ), 'setnx foo => bar fails' ); cmp_ok( $o->get( 'foo' ), 'eq', 'bar', 'get foo = bar' ); +SKIP: { + skip "set REDIS_RESTART to init script location to test reconnect code", 1 unless $ENV{REDIS_RESTART}; + + diag( 'Restarting redis server' ); + $o->save(); + + `sudo $ENV{REDIS_RESTART} restart`; + + cmp_ok( $o->get( 'foo' ), 'eq', 'bar', 'get foo = bar still works after restart' ); +} + ok( $o->set( foo => 'baz' ), 'set foo => baz' ); cmp_ok( $o->get( 'foo' ), 'eq', 'baz', 'get foo = baz' ); diff --git a/t/20-Redis-Hash.t b/t/20-Redis-Hash.t index 169eda4..785ac10 100755 --- a/t/20-Redis-Hash.t +++ b/t/20-Redis-Hash.t @@ -18,12 +18,12 @@ $o->CLEAR(); ok( ! keys %h, 'empty' ); +my $commands_processed_before = $o->info->{total_commands_processed}; + ok( %h = ( 'foo' => 42, 'bar' => 1, 'baz' => 99 ), '=' ); is_deeply( [ sort keys %h ], [ 'bar', 'baz', 'foo' ], 'keys' ); is_deeply( \%h, { bar => 1, baz => 99, foo => 42, }, 'structure' ); -ok( my $mem = $o->info->{used_memory}, 'info' ); -diag "used memory $mem"; - +ok( $commands_processed_before < $o->info->{total_commands_processed}, 'more processed commands than before' ); -- 2.20.1