NAME
AnyEvent::Redis::RipeRedis - Flexible non-blocking Redis client with reconnect feature
SYNOPSIS
use AnyEvent;
use AnyEvent::Redis::RipeRedis qw( :err_codes );
my $cv = AnyEvent->condvar();
my $redis = AnyEvent::Redis::RipeRedis->new(
host => 'localhost',
port => '6379',
password => 'your_password',
encoding => 'utf8',
on_connect => sub {
print "Connected to Redis server\n";
},
on_disconnect => sub {
print "Disconnected from Redis server\n";
},
on_error => sub {
my $err_msg = shift;
my $err_code = shift;
warn "$err_msg. Error code: $err_code\n";
},
);
# Set value
$redis->set( 'foo', 'Some string', {
on_done => sub {
print "SET is done\n";
$cv->send();
},
on_error => sub {
my $err_msg = shift;
my $err_code = shift;
$cv->croak( "$err_msg. Error code: $err_code" );
}
} );
$cv->recv();
$redis->disconnect();
DESCRIPTION
AnyEvent::Redis::RipeRedis is a non-blocking flexible Redis client with reconnect feature. It supports subscriptions, transactions and has simple API.
Requires Redis 1.2 or higher, and any supported event loop.
CONSTRUCTOR
new()
my $redis = AnyEvent::Redis::RipeRedis->new(
host => 'localhost',
port => '6379',
password => 'your_password',
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;
warn "$err_msg\n";
},
on_error => sub {
my $err_msg = shift;
my $err_code = shift;
warn "$err_msg. Error code: $err_code\n";
},
);
- host
-
Server hostname (default: 127.0.0.1)
- port
-
Server port (default: 6379)
- password
-
Authentication password. If it specified, then
AUTHcommand will be send immediately to the server after connection and after every reconnection. - database
-
Database index. If it set, then client will be switched to specified database immediately after connection and after every reconnection.
Default database index is
0. - connection_timeout
-
If after this timeout client could not connect to the server, callback
on_erroris called with error codeE_CANT_CONN.By default used kernel's connection timeout.
- read_timeout
-
If after this timeout client do not received response from the server on any command, callback
on_erroris called with error codeE_READ_TIMEOUT.Not set by default.
- lazy
-
If this parameter is set, then connection will be established, when you will send a first command to the server. By default connection establishes after calling method
new. - reconnect
-
If this parameter is TRUE and connection to the Redis server was lost, then client will try to reconnect to server while executing next command. Client try to reconnect only once and if fails, calls
on_errorcallback. If you need several attempts of reconnection, just retry command fromon_errorcallback as many times, as you need. This feature made client more responsive.By default is TRUE.
- encoding
-
Used to encode an decode strings during input/output operations.
Not set by default.
- on_connect => $cb->()
-
Callback
on_connectis called, when connection is successfully established.Not set by default.
- on_disconnect => $cb->()
-
Callback
on_disconnectis called, when connection is closed by any reason.Not set by default.
- on_connect_error => $cb->( $err_msg )
-
Callback
on_connect_erroris called, when the connection could not be established. If this collback isn't specified, thenon_errorcallback is called with error codeE_CANT_CONN. - on_error => $cb->( $err_msg, $err_code )
-
Callback
on_erroris called, when any error occurred. If callback is no set, client just print error message toSTDERR.
COMMAND EXECUTION
<command>( [ @args[, \%callbacks ] ] )
Full list of Redis commands can be found here: http://redis.io/commands.
# Set value
$redis->set( 'foo', 'Some string' );
# Increment
$redis->incr( 'bar', {
on_done => sub {
my $data = shift;
print "$data\n";
},
} );
# Get list of values
$redis->lrange( 'list', 0, -1, {
on_done => sub {
my $data = shift;
foreach my $val ( @{$data} ) {
print "$val\n";
}
},
on_error => sub {
my $err_msg = shift;
my $err_code = shift;
$cv->croak( "$err_msg. Error code: $err_code" );
},
} );
- on_done => $cb->( [ $data ] )
-
Callback
on_doneis called, when current operation is done. - on_error => $cb->( $err_msg, $err_code )
-
Callback
on_erroris called, when any error occurred.
TRANSACTIONS
Detailed information abount Redis transactions can be found here: http://redis.io/topics/transactions.
multi( [ \%callbacks ] )
Marks the start of a transaction block. Subsequent commands will be queued for atomic execution using EXEC.
exec( [ \%callbacks ] )
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.
discard( [ \%callbacks ] )
Flushes all previously queued commands in a transaction and restores the connection state to normal.
If WATCH was used, DISCARD unwatches all keys.
watch( @keys[, \%callbacks ] )
Marks the given keys to be watched for conditional execution of a transaction.
unwatch( [ \%callbacks ] )
Forget about all watched keys.
SUBSCRIPTIONS
Detailed information about Redis Pub/Sub can be found here: http://redis.io/topics/pubsub
subscribe( @channels[, \%callbacks ] )
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.
$redis->subscribe( qw( ch_foo ch_bar ), {
on_done => sub {
my $ch_name = shift;
my $subs_num = shift;
print "Subscribed: $ch_name. Active: $subs_num\n";
},
on_message => sub {
my $ch_name = shift;
my $msg = shift;
print "$ch_name: $msg\n";
},
on_error => sub {
my $err_msg = shift;
my $err_code = shift;
$cv->croak( "$err_msg. Error code: $err_code" );
},
} );
- on_done => $cb->( $ch_name, $sub_num )
-
Callback
on_doneis called, when subscription operation is done. - on_message => $cb->( $ch_name, $msg )
-
Callback
on_messageis called, when published message is received. - on_error => $cb->( $err_msg, $err_code )
-
Callback
on_erroris called, when subscription operation failed.
psubscribe( @patterns[, \%callbacks ] )
Subscribes the client to the given patterns.
$redis->psubscribe( qw( info_* err_* ), {
on_done => sub {
my $ch_pattern = shift;
my $subs_num = shift;
print "Subscribed: $ch_pattern. Active: $subs_num\n";
},
on_message => sub {
my $ch_name = shift;
my $msg = shift;
my $ch_pattern = shift;
print "$ch_name ($ch_pattern): $msg\n";
},
on_error => sub {
my $err_msg = shift;
my $err_code = shift;
$cv->croak( "$err_msg. Error code: $err_code" );
},
} );
- on_done => $cb->( $ch_pattern, $sub_num )
-
Callback
on_doneis called, when subscription operation is done. - on_message => $cb->( $ch_name, $msg, $ch_pattern )
-
Callback
on_messageis called, when published message is received. - on_error => $cb->( $err_msg, $err_code )
-
Callback
on_erroris called, when subscription operation failed.
publish( $channel, $message[, \%callbacks ] )
Posts a message to the given channel.
unsubscribe( [ @channels ][, \%callbacks ] )
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.
punsubscribe( [ @patterns ][, \%callbacks ] )
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.
CONNECTION VIA UNIX-SOCKET
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.
my $redis = AnyEvent::Redis::RipeRedis->new(
host => 'unix/',
port => '/tmp/redis.sock',
);
LUA SCRIPTS EXECUTION
Redis 2.6 and higher support execution of the 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 special method eval_cached().
eval_cached( $script, $numkeys[, [ @keys, ] [ @args, ] \%callbacks ] );
When you call eval_cached() method, client first generate SHA1 hash for the Lua script and cache it in memory. Then client optimistically send EVALSHA command under the hood. If NO_SCRIPT error will be returned, client send EVAL command.
If you call eval_cached() method with the same Lua script, client don't generate SHA1 hash for this script repeatedly, it gets hash from cache.
$redis->eval_cached( 'return { KEYS[1], KEYS[2], ARGV[1], ARGV[2] }',
2, 'key1', 'key2', 'first', 'second', {
on_done => sub {
my $data = shift;
foreach my $val ( @{$data} ) {
print "$val\n";
}
}
} );
ERROR CODES
Every time when on_error callback is called, current error code passed to it in second argument. Error codes can be used for programmatic handling of errors.
AnyEvent::Redis::RipeRedis provides constants of error codes, that can be imported and used in expressions.
use AnyEvent::Redis::RipeRedis qw( :err_codes );
- E_CANT_CONN
-
Can't connect to server. If this error occurred, client abort all operations.
- E_LOADING_DATASET
-
Redis is loading the dataset in memory.
- E_IO
-
Input/Output operation error. If this error occurred, client abort all operations and close the connection.
- E_CONN_CLOSED_BY_REMOTE_HOST
-
Connection closed by remote host. If this error occurred, client abort all operations.
- E_CONN_CLOSED_BY_CLIENT
-
Connection closed unexpectedly by client.
Error occurs, if at time of disconnection in client queue were uncompleted operations.
- E_NO_CONN
-
No connection to the server.
Error occurs, if at time of command execution connection has been closed by any reason and parameter
reconnectwas set to FALSE. - E_INVALID_PASS
-
Invalid password.
- E_OPRN_NOT_PERMITTED
-
Operation not permitted.
- E_OPRN_ERROR
-
Operation error. Usually returned by the Redis server.
- E_UNEXPECTED_DATA
-
Client received unexpected data from the server. If this error occurred, client abort all operations and close the connection.
- E_NO_SCRIPT
-
No matching script. Use
EVALcommand. - E_READ_TIMEDOUT
-
Read timed out. If this error occurred, client abort all operations and close the connection.
DISCONNECTION
When the connection to the server is no longer needed you can close it in three ways: call method disconnect(), send QUIT command or you can just "forget" any references to an AnyEvent::Redis::RipeRedis object, but in this case client object destroying silently without calling any callbacks including on_disconnect callback to avoid unexpected behavior.
disconnect()
Method for synchronous disconnection.
$redis->disconnect();
SEE ALSO
AnyEvent, AnyEvent::Redis, Redis, Redis::hiredis, RedisDB
AUTHOR
Eugene Ponizovsky, <ponizovsky@gmail.com>
Special thanks
Alexey Shrub
Vadim Vlasov
Konstantin Uvarin
COPYRIGHT AND LICENSE
Copyright (c) 2012, 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.