Redis - Perl binding for Redis database
version 1.955
## Defaults to $ENV{REDIS_SERVER} or 127.0.0.1:6379 my $redis = Redis->new; my $redis = Redis->new(server => 'redis.example.com:8080'); ## Use UNIX domain socket my $redis = Redis->new(sock => '/path/to/socket'); ## Enable auto-reconnect ## Try to reconnect every 500ms up to 60 seconds until success ## Die if you can't after that my $redis = Redis->new(reconnect => 60); ## Try each 100ms upto 2 seconds (every is in milisecs) my $redis = Redis->new(reconnect => 2, every => 100); ## Disable the automatic utf8 encoding => much more performance ## !!!! This will be the default after 2.000, see ENCODING below my $redis = Redis->new(encoding => undef); ## Use all the regular Redis commands, they all accept a list of ## arguments ## See http://redis.io/commands for full list $redis->get('key'); $redis->set('key' => 'value'); $redis->sort('list', 'DESC'); $redis->sort(qw{list LIMIT 0 5 ALPHA DESC}); ## Add a coderef argument to run a command in the background $redis->sort(qw{list LIMIT 0 5 ALPHA DESC}, sub { my ($reply, $error) = @_; die "Oops, got an error: $error\n" if defined $error; print "$_\n" for @$reply; }); long_computation(); $redis->wait_all_responses; ## Or run a large batch of commands in a pipeline my %hash = _get_large_batch_of_commands(); $redis->hset('h', $_, $hash{$_}, sub {}) for keys %hash; $redis->wait_all_responses; ## Publish/Subscribe $redis->subscribe( 'topic_1', 'topic_2', sub { my ($message, $topic, $subscribed_topic) = @_ ## $subscribed_topic can be different from topic if ## you use psubscribe() with wildcards } ); $redis->psubscribe('nasdaq.*', sub {...}); ## Blocks and waits for messages, calls subscribe() callbacks ## ... forever my $timeout = 10; $redis->wait_for_messages($timeout) while 1; ## ... until some condition my $keep_going = 1; ## other code will set to false to quit $redis->wait_for_messages($timeout) while $keep_going; $redis->publish('topic_1', 'message');
Pure perl bindings for http://redis.io/
This version supports protocol 2.x (multi-bulk) or later of Redis available at https://github.com/antirez/redis/.
This documentation lists commands which are exercised in test suite, but additional commands will work correctly since protocol specifies enough information to support almost all commands with same piece of code with a little help of AUTOLOAD.
AUTOLOAD
Usually, running a command will wait for a response. However, if you're doing large numbers of requests, it can be more efficient to use what Redis calls pipelining: send multiple commands to Redis without waiting for a response, then wait for the responses that come in.
To use pipelining, add a coderef argument as the last argument to a command method call:
$r->set('foo', 'bar', sub {});
Pending responses to pipelined commands are processed in a single batch, as soon as at least one of the following conditions holds:
A non-pipelined (synchronous) command has been sent on the same connection
A pub/sub subscription command (one of subscribe, unsubscribe, psubscribe, or punsubscribe) is about to be sent on the same connection.
subscribe
unsubscribe
psubscribe
punsubscribe
The "wait_all_responses" method is called explicitly.
The coderef you supply to a pipelined command method is invoked once the response is available. It takes two arguments, $reply and $error. If $error is defined, it contains the text of an error reply sent by the Redis server. Otherwise, $reply is the non-error reply. For almost all commands, that means it's undef, or a defined but non-reference scalar, or an array ref of any of those; but see "keys", "info", and "exec".
$reply
$error
undef
Note the contrast with synchronous commands, which throw an exception on receipt of an error reply, or return a non-error reply directly.
The fact that pipelined commands never throw an exception can be particularly useful for Redis transactions; see "exec".
This feature is deprecated and will be removed before 2.000. You should start testing your code with encoding => undef because that will be the new default with 2.000.
encoding => undef
Since Redis knows nothing about encoding, we are forcing utf-8 flag on all data received from Redis. This change was introduced in 1.2001 version. Please note that this encoding option severely degrades performance.
You can disable this automatic encoding by passing an option to "new": encoding => undef.
This allows us to round-trip utf-8 encoded characters correctly, but might be problem if you push binary junk into Redis and expect to get it back without utf-8 flag turned on.
my $r = Redis->new; # $ENV{REDIS_SERVER} or 127.0.0.1:6379 my $r = Redis->new( server => '192.168.0.1:6379', debug => 0 ); my $r = Redis->new( server => '192.168.0.1:6379', encoding => undef ); my $r = Redis->new( sock => '/path/to/sock' ); my $r = Redis->new( reconnect => 60, every => 5000 ); my $r = Redis->new( password => 'boo' );
The server parameter specifies the Redis server we should connect to, via TCP. Use the 'IP:PORT' format. If no server option is present, we will attempt to use the REDIS_SERVER environment variable. If neither of those options are present, it defaults to '127.0.0.1:6379'.
server
REDIS_SERVER
Alternatively you can use the sock parameter to specify the path of the UNIX domain socket where the Redis server is listening.
sock
The REDIS_SERVER can be used for UNIX domain sockets too. The following formats are supported:
/path/to/sock
unix:/path/to/sock
127.0.0.1:11011
tcp:127.0.0.1:11011
The encoding parameter speficies the encoding we will use to decode all the data we receive and encode all the data sent to the redis server. Due to backwards-compatibility we default to utf8. To disable all this encoding/decoding, you must use <encoding = undef>>. This is the recommended option.
encoding
utf8
<encoding =
Warning: this option has several problems and it is deprecated. A future version might add other filtering options though.
The reconnect option enables auto-reconnection mode. If we cannot connect to the Redis server, or if a network write fails, we enter retry mode. We will try a new connection every every miliseconds (1000ms by default), up-to reconnect seconds.
reconnect
every
Be aware that read errors will always thrown an exception, and will not trigger a retry until the new command is sent.
If we cannot re-establish a connection after reconnect seconds, an exception will be thrown.
If your Redis server requires authentication, you can use the password attribute. After each established connection (at the start or when reconnecting), the Redis AUTH command will be send to the server. If the password is wrong, an exception will be thrown and reconnect will be disabled.
password
AUTH
The debug parameter enables debug information to STDERR, including all interactions with the server. You can also enable debug with the REDIS_DEBUG environment variable.
debug
REDIS_DEBUG
$r->quit;
Closes the connection to the server. The quit method does not support pipelined operation.
quit
$r->ping || die "no server?";
The ping method does not support pipelined operation.
ping
Waits until all pending pipelined responses have been received, and invokes the pipeline callback for each one. See "PIPELINING".
Warning: the behaviour of these commands when combined with pipelining is still under discussion, and you should NOT use them at the same time just now.
You can follow the discussion to see the open issues with this.
$r->multi;
$r->discard;
my @individual_replies = $r->exec;
exec has special behaviour when run in a pipeline: the $reply argument to the pipeline callback is an array ref whose elements are themselves [$reply, $error] pairs. This means that you can accurately detect errors yielded by any command in the transaction, and without any exceptions being thrown.
exec
[$reply, $error]
$r->set( foo => 'bar' ); $r->setnx( foo => 42 );
my $value = $r->get( 'foo' );
my @values = $r->mget( 'foo', 'bar', 'baz' );
$r->incr('counter'); $r->incrby('tripplets', 3);
$r->decr('counter'); $r->decrby('tripplets', 3);
$r->exists( 'key' ) && print "got key!";
$r->del( 'key' ) || warn "key doesn't exist";
$r->type( 'key' ); # = string
my @keys = $r->keys( '*glob_pattern*' ); my $keys = $r->keys( '*glob_pattern*' ); # count of matching keys
Note that synchronous keys calls in a scalar context return the number of matching keys (not an array ref of matching keys as you might expect). This does not apply in pipelined mode: assuming the server returns a list of keys, as expected, it is always passed to the pipeline callback as an array ref.
keys
my $key = $r->randomkey;
my $ok = $r->rename( 'old-key', 'new-key', $new );
my $nr_keys = $r->dbsize;
See also Redis::List for tie interface.
$r->rpush( $key, $value );
$r->lpush( $key, $value );
$r->llen( $key );
my @list = $r->lrange( $key, $start, $end );
my $ok = $r->ltrim( $key, $start, $end );
$r->lindex( $key, $index );
$r->lset( $key, $index, $value );
my $modified_count = $r->lrem( $key, $count, $value );
my $value = $r->lpop( $key );
my $value = $r->rpop( $key );
my $ok = $r->sadd( $key, $member );
my $n_elements = $r->scard( $key );
my @elements = $r->sdiff( $key1, $key2, ... ); my $elements = $r->sdiff( $key1, $key2, ... ); # ARRAY ref
my $ok = $r->sdiffstore( $dstkey, $key1, $key2, ... );
my @elements = $r->sinter( $key1, $key2, ... ); my $elements = $r->sinter( $key1, $key2, ... ); # ARRAY ref
my $ok = $r->sinterstore( $dstkey, $key1, $key2, ... );
my $bool = $r->sismember( $key, $member );
my @elements = $r->smembers( $key ); my $elements = $r->smembers( $key ); # ARRAY ref
my $ok = $r->smove( $srckey, $dstkey, $element );
my $element = $r->spop( $key );
my $element = $r->srandmember( $key );
$r->srem( $key, $member );
my @elements = $r->sunion( $key1, $key2, ... ); my $elements = $r->sunion( $key1, $key2, ... ); # ARRAY ref
my $ok = $r->sunionstore( $dstkey, $key1, $key2, ... );
$r->sort("key BY pattern LIMIT start end GET pattern ASC|DESC ALPHA');
When one of "subscribe" or "psubscribe" is used, the Redis object will enter PubSub mode. When in PubSub mode only commands in this section, plus "quit", will be accepted.
If you plan on using PubSub and other Redis functions, you should use two Redis objects, one dedicated to PubSub and the other for regular commands.
All Pub/Sub commands receive a callback as the last parameter. This callback receives three arguments:
The published message.
The topic over which the message was sent.
The subscribed topic that matched the topic for the message. With "subscribe" these last two are the same, always. But with "psubscribe", this parameter tells you the pattern that matched.
See the Pub/Sub notes for more information about the messages you will receive on your callbacks after each "subscribe", "unsubscribe", "psubscribe" and "punsubscribe".
$r->publish($topic, $message);
Publishes the $message to the $topic.
$message
$topic
$r->subscribe( @topics_to_subscribe_to, sub { my ($message, $topic, $subscribed_topic) = @_; ... }, );
Subscribe one or more topics. Messages published into one of them will be received by Redis, and the specificed callback will be executed.
$r->unsubscribe(@topic_list, sub { my ($m, $t, $s) = @_; ... });
Stops receiving messages for all the topics in @topic_list.
@topic_list
my @topic_matches = ('prefix1.*', 'prefix2.*'); $r->psubscribe(@topic_matches, sub { my ($m, $t, $s) = @_; ... });
Subscribes a pattern of topics. All messages to topics that match the pattern will be delivered to the callback.
my @topic_matches = ('prefix1.*', 'prefix2.*'); $r->punsubscribe(@topic_matches, sub { my ($m, $t, $s) = @_; ... });
Stops receiving messages for all the topics pattern matches in @topic_list.
if ($r->is_subscriber) { say "We are in Pub/Sub mode!" }
Returns true if we are in Pub/Sub mode.
my $keep_going = 1; ## Set to false somewhere to leave the loop my $timeout = 5; $r->wait_for_messages($timeout) while $keep_going;
Blocks, waits for incoming messages and delivers them to the appropriate callbacks.
Requires a single parameter, the number of seconds to wait for messages. Use 0 to wait for ever. If a positive non-zero value is used, it will return after that ammount of seconds without a single notification.
Please note that the timeout is not a commitement to return control to the caller at most each timeout seconds, but more a idle timeout, were control will return to the caller if Redis is idle (as in no messages were received during the timeout period) for more than timeout seconds.
timeout
The "wait_for_messages" call returns the number of messages processed during the run.
$r->save;
$r->bgsave;
$r->lastsave;
$r->eval($lua_script, $num_keys, $key1, ..., $arg1, $arg2);
Executes a Lua script server side.
Note that this commands sends the Lua script every time you call it. See "evalsha" and "script_load" for an alternative.
$r->eval($lua_script_sha1, $num_keys, $key1, ..., $arg1, $arg2);
Executes a Lua script cached on the server side by its SHA1 digest.
See "script_load".
my ($sha1) = $r->script_load($lua_script);
Cache Lua script, returns SHA1 digest that can be used with "evalsha".
my ($exists1, $exists2, ...) = $r->script_exists($scrip1_sha, $script2_sha, ...);
Given a list of SHA1 digests, returns a list of booleans, one for each SHA1, that report the existence of each script in the server cache.
$r->script_kill;
Kills the currently running script.
$r->script_flush;
Flush the Lua scripts cache.
my $info_hash = $r->info;
The info method is unique in that it decodes the server's response into a hashref, if possible. This decoding happens in both synchronous and pipelined modes.
info
$r->shutdown;
The shutdown method does not support pipelined operation.
shutdown
$r->select( $dbindex ); # 0 for new clients
$r->move( $key, $dbindex );
$r->flushdb;
$r->flushall;
You can find documentation for this module with the perldoc command.
perldoc Redis
The following websites have more information about this module, and may be of help to you. As always, in addition to those websites please use your favorite search engine to discover more resources.
CPAN Testers
The CPAN Testers is a network of smokers who run automated tests on uploaded CPAN distributions.
http://www.cpantesters.org/distro/R/Redis
CPAN Testers Matrix
The CPAN Testers Matrix is a website that provides a visual overview of the test results for a distribution on various Perls/platforms.
http://matrix.cpantesters.org/?dist=Redis
CPAN Testers Dependencies
The CPAN Testers Dependencies is a website that shows a chart of the test results of all dependencies for a distribution.
http://deps.cpantesters.org/?module=Redis
CPAN Ratings
The CPAN Ratings is a website that allows community ratings and reviews of Perl modules.
http://cpanratings.perl.org/d/Redis
You can email the author of this module at MELO at cpan.org asking for help with any problems you have.
MELO at cpan.org
Please report any bugs or feature requests by email to bug-redis at rt.cpan.org, or through the web interface at http://rt.cpan.org/Public/Dist/Display.html?Name=Redis. You will be automatically notified of any progress on the request by the system.
bug-redis at rt.cpan.org
https://github.com/melo/perl-redis
git clone https://github.com/melo/perl-redis.git
The following persons contributed to this project (alphabetical order):
Aaron Crane (pipelining and AUTOLOAD caching support)
Dirk Vleugels
Flavio Poletti
Jeremy Zawodny
sunnavy at bestpractical.com
Thiago Berlitz Rondon
Ulrich Habel
Pedro Melo <melo@cpan.org>
This software is Copyright (c) 2012 by Pedro Melo.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
To install Redis, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Redis
CPAN shell
perl -MCPAN -e shell install Redis
For more information on module installation, please visit the detailed CPAN module installation guide.