AnyEvent::Redis::RipeRedis - Flexible non-blocking Redis client with reconnect feature
use AnyEvent; use AnyEvent::Redis::RipeRedis qw( :err_codes ); my $cv = AE::cv(); my $redis = AnyEvent::Redis::RipeRedis->new( host => 'localhost', port => '6379', password => 'yourpass', on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... $cv->croak( $err_msg ); }, ); $redis->set( 'foo', 'string', { on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... $cv->croak( $err_msg ); }, } ); $redis->get( 'foo', { on_done => sub { my $reply = shift; print "$reply\n"; }, on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... $cv->croak( $err_msg ); } } ); $redis->incr( 'bar', sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... $cv->croak( $err_msg ); return; } print "$reply\n"; }, ); $redis->quit( { on_done => sub { $cv->send(); }, } ); $cv->recv();
AnyEvent::Redis::RipeRedis is the flexible non-blocking Redis client with reconnect feature. The client supports subscriptions, transactions and connection via UNIX-socket.
Requires Redis 1.2 or higher, and any supported event loop.
my $redis = AnyEvent::Redis::RipeRedis->new( host => 'localhost', port => '6379', password => 'yourpass', database => 7, lazy => 1, connection_timeout => 5, read_timeout => 5, reconnect => 1, encoding => 'utf8', on_connect => sub { print "Connected to Redis server\n"; }, on_disconnect => sub { print "Disconnected from Redis server\n"; }, on_connect_error => sub { my $err_msg = shift; # error handling ... }, on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... }, );
Server hostname (default: 127.0.0.1)
Server port (default: 6379)
If the password is specified, then the AUTH command is sent immediately to the server after every connection.
AUTH
Database index. If the index is specified, then the client is switched to the specified database immediately after every connection.
The default database index is 0.
0
Timeout, within which the client will be wait the connection establishment to the Redis server. If the client could not connect to the server after specified timeout, then the on_error or on_connect_error callback is called. In case, when on_error callback is called, E_CANT_CONN error code is passed to callback in the second argument. The timeout specifies in seconds and can contain a fractional part.
on_error
on_connect_error
E_CANT_CONN
my $redis = AnyEvent::Redis::RipeRedis->new( connection_timeout => 10.5, );
By default the client use kernel's connection timeout.
Timeout, within which the client will be wait a response on a command from the Redis server. If the client could not receive a response from the server after specified timeout, then the client close connection and call on_error callback with the E_READ_TIMEDOUT error code. The timeout is specifies in seconds and can contain a fractional part.
E_READ_TIMEDOUT
my $redis = AnyEvent::Redis::RipeRedis->new( read_timeout => 3.5, );
Not set by default.
If this parameter is set, then the connection establishes, when you will send the first command to the server. By default the connection establishes after calling of the new method.
new
If the connection to the Redis server was lost and the parameter reconnect is TRUE, then the client try to restore the connection on a next command executuion. The client try to reconnect only once and if it fails, then is called the on_error callback. If you need several attempts of the reconnection, just retry a command from the on_error callback as many times, as you need. This feature made the client more responsive.
reconnect
By default is TRUE.
Used for encode/decode strings at time of input/output operations.
The on_connect callback is called, when the connection is successfully established.
on_connect
The on_disconnect callback is called, when the connection is closed by any reason.
on_disconnect
The on_connect_error callback is called, when the connection could not be established. If this collback isn't specified, then the common on_error callback is called with the E_CANT_CONN error code.
The common on_error callback is called when ocurred some error, which was affected on entire client (e. g. connection error). Also this callback is called on other errors if neither on_error callback nor on_reply callback is specified in the command method. If common on_error callback is not specified, the client just print an error messages to STDERR.
on_reply
STDERR
The full list of the Redis commands can be found here: http://redis.io/commands.
$redis->set( 'foo', 'string' ); $redis->get( 'foo', { on_done => sub { my $reply = shift; print "$reply\n"; }, on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... } } ); $redis->lrange( 'list', 0, -1, { on_done => sub { my $reply = shift; foreach my $val ( @{$reply} ) { print "$val\n"; } }, on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... }, } ); $redis->incr( 'bar', sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... return; } print "$reply\n"; }, ); $redis->incr( 'bar', { on_reply => sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... return; } print "$reply\n"; }, } );
The on_done callback is called, when the current operation is done.
on_done
The on_error callback is called, when some error occurred.
Since version 1.300 of the client you can specify single, on_reply callback, instead of two, on_done and on_error callbacks. The on_reply callback is called in both cases: when operation was completed successfully and when some error occurred. In first case to callback is passed only reply data. In second case to callback is passed three arguments: undef value or reply data with error objects (see below), error mesage and error code.
undef
The detailed information abount the Redis transactions can be found here: http://redis.io/topics/transactions.
Marks the start of a transaction block. Subsequent commands will be queued for atomic execution using EXEC.
EXEC
Executes all previously queued commands in a transaction and restores the connection state to normal. When using WATCH, EXEC will execute commands only if the watched keys were not modified.
WATCH
If after execution of EXEC command at least one operation fails, then either on_error or on_reply callback is called with E_OPRN_ERROR error code. Additionally, to callbacks is passed reply data, which contain usual data and error objects for each failed operation. To on_error callback reply data is passed in third argument and to on_reply callback in first argument. Error object is an instance of class AnyEvent::Redis::RipeRedis::Error and has two methods: message() to get error message and code() to get error code.
E_OPRN_ERROR
AnyEvent::Redis::RipeRedis::Error
message()
code()
$redis->multi(); $redis->set( 'foo', 'string' ); $redis->incr( 'foo' ); # causes an error $redis->exec( { on_error => sub { my $err_msg = shift; my $err_code = shift; my $reply = shift; foreach my $reply ( @{$reply} ) { if ( ref( $reply ) eq 'AnyEvent::Redis::RipeRedis::Error' ) { my $oprn_err_msg = $reply->message(); my $oprn_err_code = $reply->code(); # error handling ... } } }, } ); $redis->multi(); $redis->set( 'foo', 'string' ); $redis->incr( 'foo' ); # causes an error $redis->exec( sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; foreach my $reply ( @{$reply} ) { if ( ref( $reply ) eq 'AnyEvent::Redis::RipeRedis::Error' ) { my $oprn_err_msg = $reply->message(); my $oprn_err_code = $reply->code(); # error handling ... } } } }, );
Flushes all previously queued commands in a transaction and restores the connection state to normal.
If WATCH was used, DISCARD unwatches all keys.
DISCARD
Marks the given keys to be watched for conditional execution of a transaction.
Forget about all watched keys.
The detailed information about Redis Pub/Sub can be found here: http://redis.io/topics/pubsub
Subscribes the client to the specified channels.
Once the client enters the subscribed state it is not supposed to issue any other commands, except for additional SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE and PUNSUBSCRIBE commands.
SUBSCRIBE
PSUBSCRIBE
UNSUBSCRIBE
PUNSUBSCRIBE
$redis->subscribe( qw( ch_foo ch_bar ), { on_done => sub { my $ch_name = shift; my $subs_num = shift; # subscription handling ... }, on_message => sub { my $ch_name = shift; my $msg = shift; # message handling ... }, on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... }, } ); $redis->subscribe( qw( ch_foo ch_bar ), sub { my $ch_name = shift; my $msg = shift; # message handling ... } ); $redis->subscribe( qw( ch_foo ch_bar ), { on_reply => sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... return; } my $ch_name = $reply->[0]; my $subs_num = $reply->[1]; # subscription handling ... }, on_message => sub { my $ch_name = shift; my $msg = shift; # message handling ... }, } );
The on_done callback is called on every specified channel, when the subscription operation was completed successfully.
The on_message callback is called, when a published message was received.
on_message
The on_error callback is called, if the subscription operation fails.
The on_reply callback is called in both cases: when the subscription operation was completed successfully and when subscription operation fails. In first case on_reply callback is called on every specified channel. Information about channel name and subscription number is passed to callback in first argument as an array reference.
Subscribes the client to the given patterns.
$redis->psubscribe( qw( foo_* bar_* ), { on_done => sub { my $ch_pattern = shift; my $subs_num = shift; # subscription handling ... }, on_message => sub { my $ch_name = shift; my $msg = shift; my $ch_pattern = shift; # message handling ... }, on_error => sub { my $err_msg = shift; my $err_code = shift; # error handling ... }, } ); $redis->psubscribe( qw( foo_* bar_* ), sub { my $ch_name = shift; my $msg = shift; my $ch_pattern = shift; # message handling ... } ); $redis->psubscribe( qw( foo_* bar_* ), { on_reply => sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... return; } my $ch_pattern = $reply->[0]; my $subs_num = $reply->[1]; # subscription handling ... }, on_message => sub { my $ch_name = shift; my $msg = shift; my $ch_pattern = shift; # message handling ... }, } );
The on_done callback is called on every specified pattern, when the subscription operation was completed successfully.
The on_message callback is called, when published message was received.
The on_reply callback is called in both cases: when the subscription operation was completed successfully and when subscription operation fails. In first case on_reply callback is called on every specified pattern. Information about channel pattern and subscription number is passed to callback in first argument as an array reference.
Posts a message to the given channel.
Unsubscribes the client from the given channels, or from all of them if none is given.
When no channels are specified, the client is unsubscribed from all the previously subscribed channels. In this case, a message for every unsubscribed channel will be sent to the client.
$redis->unsubscribe( qw( ch_foo ch_bar ), { on_done => sub { my $ch_name = shift; my $subs_num = shift; # unsubscription handling ... }, } ); $redis->unsubscribe( qw( ch_foo ch_bar ), sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... return; } my $ch_name = $reply->[0]; my $subs_num = $reply->[1]; # unsubscription handling ... } );
The on_done callback is called on every specified channel, when the unsubscription operation was completed successfully.
The on_error callback is called, if the unsubscription operation fails.
The on_reply callback is called in both cases: when the unsubscription operation was completed successfully and when unsubscription operation fails. In first case on_reply callback is called on every specified channel. Information about channel name and number of remaining subscriptions is passed to callback in first argument as an array reference.
Unsubscribes the client from the given patterns, or from all of them if none is given.
When no patters are specified, the client is unsubscribed from all the previously subscribed patterns. In this case, a message for every unsubscribed pattern will be sent to the client.
$redis->punsubscribe( qw( foo_* bar_* ), { on_done => sub { my $ch_pattern = shift; my $subs_num = shift; # unsubscription handling ... }, } ); $redis->punsubscribe( qw( foo_* bar_* ), sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; # error handling ... return; } my $ch_pattern = $reply->[0]; my $subs_num = $reply->[1]; # unsubscription handling ... } );
The on_done callback is called on every specified pattern, when the unsubscription operation was completed successfully.
The on_reply callback is called in both cases: when the unsubscription operation was completed successfully and when unsubscription operation fails. In first case on_reply callback is called on every specified pattern. Information about channel pattern and number of remaining subscriptions is passed to callback in first argument as an array reference.
Redis 2.2 and higher support connection via UNIX domain socket. To connect via a UNIX-socket in the parameter host you have to specify unix/, and in the parameter port you have to specify the path to the socket.
host
unix/
port
my $redis = AnyEvent::Redis::RipeRedis->new( host => 'unix/', port => '/tmp/redis.sock', );
Redis 2.6 and higher support execution of Lua scripts on the server side. To execute a Lua script you can use one of the commands EVAL or EVALSHA, or you can use the special method eval_cached().
EVAL
EVALSHA
eval_cached()
If Lua script returns multi-bulk reply with at least one error reply, then either on_error or on_reply callback is called with E_OPRN_ERROR error code. Additionally, to callbacks is passed reply data, which contain usual data and error objects for each error reply, as well as described for EXEC command.
$redis->eval( "return { 'foo', redis.error_reply( 'Error.' ) }", 0, { on_error => sub { my $err_msg = shift; my $err_code = shift; my $reply = shift; foreach my $reply ( @{$reply} ) { if ( ref( $reply ) eq 'AnyEvent::Redis::RipeRedis::Error' ) { my $nested_err_msg = $reply->message(); my $nested_err_code = $reply->code(); # error handling ... } } } } ); $redis->eval( "return { 'foo', redis.error_reply( 'Error.' ) }", 0, sub { my $reply = shift; my $err_msg = shift; if ( defined( $err_msg ) ) { my $err_code = shift; foreach my $reply ( @{$reply} ) { if ( ref( $reply ) eq 'AnyEvent::Redis::RipeRedis::Error' ) { my $nested_err_msg = $reply->message(); my $nested_err_code = $reply->code(); # error handling ... } } } } );
When you call the eval_cached() method, the client first generate a SHA1 hash for a Lua script and cache it in memory. Then the client optimistically send the EVALSHA command under the hood. If the NO_SCRIPT error will be returned, the client send the EVAL command.
NO_SCRIPT
If you call the eval_cached() method with the same Lua script, client don not generate a SHA1 hash for this script repeatedly, it gets a hash from the cache instead.
$redis->eval_cached( 'return { KEYS[1], KEYS[2], ARGV[1], ARGV[2] }', 2, 'key1', 'key2', 'first', 'second', { on_done => sub { my $reply = shift; foreach my $val ( @{$reply} ) { print "$val\n"; } } } );
Be care, passing a different Lua scripts to eval_cached() method every time cause memory leaks.
Every time when error occurred the error code is passed to on_error or to on_reply callback. Error codes can be used for programmatic handling of errors.
AnyEvent::Redis::RipeRedis provides constants of error codes, which can be imported and used in expressions.
use AnyEvent::Redis::RipeRedis qw( :err_codes );
Can't connect to the server. All operations were aborted.
Redis is loading the dataset in memory.
Input/Output operation error. The connection to the Redis server was closed and all operations were aborted.
The connection closed by remote host. All operations were aborted.
Uncompleted operations were aborted at time of calling disconnect() method or after executing QUIT command.
disconnect()
QUIT
No connection to the Redis server. Connection was lost by any reason on previous operation.
Operation error. For example, wrong number of arguments for a command.
The client received unexpected data from the server. The connection to the Redis server was closed and all operations were aborted.
Read timed out. The connection to the Redis server was closed and all operations were aborted.
Error codes available since Redis 2.6.
No matching script. Use the EVAL command.
Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.
SCRIPT KILL
SHUTDOWN NOSAVE
Link with MASTER is down and slave-serve-stale-data is set to 'no'.
Redis is configured to save RDB snapshots, but is currently not able to persist on disk. Commands that may modify the data set are disabled. Please check Redis logs for details about the error.
You can't write against a read only slave.
Command not allowed when used memory > 'maxmemory'.
Transaction discarded because of previous errors.
Error codes available since Redis 2.8.
Authentication required.
Operation against a key holding the wrong kind of value.
Not enough good slaves to write.
When the connection to the server is no longer needed you can close it in three ways: call the method disconnect(), send the QUIT command or you can just "forget" any references to an AnyEvent::Redis::RipeRedis object, but in this case a client object is destroyed without calling any callbacks including the on_disconnect callback to avoid an unexpected behavior.
The method for synchronous disconnection. Not completed operations will be aborted.
$redis->disconnect();
The method for asynchronous disconnection. All commands, executed before this method, will be completed correctly.
my $cv = AE::cv(); $redis->set( 'foo', 'string' ); $redis->incr( 'bar' ); $redis->quit( sub { $cv->send(); } ); $cv->recv();
Get or set the connection_timeout of the client. undef value resets the connection_timeout to default value.
connection_timeout
Get or set the read_timeout of the client.
read_timeout
Enable or disable reconnection mode of the client.
Get or set the current encoding of the client.
encoding
Get or set the on_connect callback.
Get or set the on_disconnect callback.
Get or set the on_connect_error callback.
Get or set the on_error callback.
AnyEvent, AnyEvent::Redis, Redis, Redis::hiredis, RedisDB
Eugene Ponizovsky, <ponizovsky@gmail.com>
Alexey Shrub
Vadim Vlasov
Konstantin Uvarin
Copyright (c) 2012-2013, Eugene Ponizovsky, <ponizovsky@gmail.com>. All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install AnyEvent::Redis::RipeRedis, copy and paste the appropriate command in to your terminal.
cpanm
cpanm AnyEvent::Redis::RipeRedis
CPAN shell
perl -MCPAN -e shell install AnyEvent::Redis::RipeRedis
For more information on module installation, please visit the detailed CPAN module installation guide.