AnyEve...peRedis(3pm)

πŸ“¦
version 0.48 Β· 3 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

✨ NAME ✨

AnyEvent::RipeRedis β€” Flexible non-blocking Redis client πŸ’…

Okay bestie, if you're here it's because you want your Perl app to talk to Redis without blocking the whole event loop while it waits, and honestly? Taste. πŸ‘‘


πŸ¦‹ SYNOPSIS πŸ¦‹

use AnyEvent;
use AnyEvent::RipeRedis;

my $redis = AnyEvent::RipeRedis->new(
  host     => 'localhost',
  port     => 6379,
  password => 'yourpass',
);

my $cv = AE::cv;

$redis->set( 'foo', 'bar',
  sub {
    my $err = $_[1];

    if ( defined $err ) {
      warn $err->message . "\n";
      $cv->send;

      return;
    }

    $redis->get( 'foo',
      sub {
        my $reply = shift;
        my $err   = shift;

        if ( defined $err ) {
          warn $err->message . "\n";
          $cv->send;

          return;
        }

        print "$reply\n";
        $cv->send;
      }
    );
  }
);

$cv->recv;

🌸 DESCRIPTION 🌸

AnyEvent::RipeRedis is a flexible non-blocking Redis client. She does subscriptions, she does transactions, and she can automaticaly restore your connection after a failure β€” like a bestie who fixes your eyeliner without even being asked. πŸ’–

She requires Redis 1.2 or higher, plus any supported event loop. No cap. ✨


πŸ‘‘ CONSTRUCTOR πŸ‘‘

new( %params )

my $redis = AnyEvent::RipeRedis->new(
  host               => 'localhost',
  port               => 6379,
  password           => 'yourpass',
  database           => 7,
  connection_timeout => 5,
  read_timeout       => 5,
  lazy               => 1,
  reconnect_interval => 5,

  on_connect => sub {
    # handling...
  },

  on_disconnect => sub {
    # handling...
  },

  on_error => sub {
    my $err = shift;

    # error handling...
  },
);

Now let's go through every single one of these, because we do not skip params in this house 🏠✨

  • host => $host β€” the server hostname. Default is 127.0.0.1 (yes, she assumes localhost, so confident of her).
  • port => $port β€” the server port. Default is 6379.
  • password => $password β€” if you hand her a password, the AUTH command gets sent to the server right after connection. πŸ”
  • database => $index β€” the database index. If you specify it, the client switches to that database after connecting. You can also hop to a different database later with the SELECT command. And here's the cute part: the client remembers the last selected database after reconnection and switches back to it automaticaly. The default database index is 0.
  • utf8 => $boolean β€” if enabled, every string gets converted to UTF-8 before it's sent to the server, and every result gets decoded from UTF-8 on the way back. Enabled by default. 🌈
  • connection_timeout => $fractional_seconds β€” how long she waits to connect. If she can't reach the server within the specified timeout, the on_error callback fires with the E_CANT_CONN error. The timeout is in seconds and can totally have a fractional part:
connection_timeout => 10.5,

By default the client uses the kernel's connection timeout.

  • read_timeout => $fractional_seconds β€” how long she waits for a reply. If she can't get one from the server within the specified timeout, the client closes the connection and calls the on_error callback with the E_READ_TIMEDOUT error. Also in seconds, also fractional-friendly:
read_timeout => 3.5,

Not set by default.

  • lazy => $boolean β€” if enabled, the connection only establishes when you send the first command to the server. Otherwise (the default behavior) the connection establishes right after the new method is called. Disabled by default. 😴
  • reconnect => $boolean β€” if the connection to the server was lost and reconnect is TRUE (which it is by default), the client will try to restore the connection when you execute the next command. She tries to reconnect only once, and if that attempt fails, the error object gets passed to the command callback. Need more than one attempt? You retry the command from the callback as many times as you need β€” that's the whole point, it lets you control the reconnection procedure. Enabled by default.
  • reconnect_interval => $fractional_seconds β€” if you set this, the client will only try to reconnect after this interval. Any commands executed between reconnections get queued up patiently. 🫢
reconnect_interval => 5,

Not set by default.

  • handle_params => \%params β€” here's where you pass AnyEvent::Handle parameters:
handle_params => {
  autocork => 1,
  linger   => 60,
}

Turning on the autocork parameter can improve performance. Go read the AnyEvent::Handle documentation for more info. πŸ“š

  • on_connect => $cb->() β€” this callback gets called when the connection is successfully established. Not set by default.
  • on_disconnect => $cb->() β€” this callback gets called when the connection is closed, for any reason. Not set by default.
  • on_error => $cb->( $err ) β€” this callback gets called when an error occurs that affects the entire client (think: connection error or authentication error). It's also called on command errors if the command callback isn't specified. And if you don't set on_error at all? The client just prints error messages to STDERR. πŸ’€

πŸ’… COMMAND EXECUTION πŸ’…

<command>( [ @args ] [, $cb->( $reply, $err ) ] )

To execute a command, you call the specific method with the corresponding name. The reply to the command gets passed to the callback as the first argument. If any error happened during execution, the error object lands in the callback as the second argument. That error object is an instance of the class AnyEvent::RipeRedis::Error.

The command callback is optional β€” but if you skip it and an error happens, the client's on_error callback gets called instead. πŸ‘€

The full list of Redis commands lives here: http://redis.io/commands

$redis->get( 'foo',
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      my $err_msg  = $err->message;
      my $err_code = $err->code;

      # error handling...

      return;
    }

    print "$reply\n";
  }
);
$redis->lrange( 'list', 0, -1,
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      my $err_msg  = $err->message;
      my $err_code = $err->code;

      # error handling...

      return;
    }

    foreach my $value ( @{$reply}  ) {
      print "$value\n";
    }
  }
);

And look at this β€” no callback at all, just vibes:

$redis->incr( 'counter' );

You can execute multi-word commands like this:

$redis->client_getname(
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      my $err_msg  = $err->message;
      my $err_code = $err->code;

      # error handling...

      return;
    }

    print "$reply\n";
  }
);

execute( $command, [ @args ] [, $cb->( $reply, $err ) ] )

An alternative method for executing commands. In some cases it's just more convenient, and honestly? Slay. πŸ’…

$redis->execute( 'get', 'foo',
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      my $err_msg  = $err->message;
      my $err_code = $err->code;

      return;
    }

    print "$reply\n";
  }
);

πŸ”₯ TRANSACTIONS πŸ”₯

The detailed info about Redis transactions lives here: http://redis.io/topics/transactions

multi( [ $cb->( $reply, $err ) ] )

Marks the start of a transaction block. Everything you send after this gets queued up for atomic execution using EXEC. πŸŽ€

exec( [ $cb->( $reply, $err ) ] )

Executes all the previously queued commands in the transaction and restores the connection state back to normal. And if you're using WATCH, EXEC will only execute the commands if the watched keys weren't modified. ✨

If at least one command fails during a transaction, the callback receives an error object, and the reply will contain nested error objects for every failed command. Yes, errors inside errors. It's giving inception. πŸŒ€

$redis->multi();
$redis->set( 'foo', 'string' );
$redis->incr('foo');    # causes an error
$redis->exec(
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      my $err_msg  = $err->message();
      my $err_code = $err->code();

      if ( defined $reply ) {
        foreach my $nested_reply ( @{$reply} ) {
          if ( ref($nested_reply) eq 'AnyEvent::RipeRedis::Error' ) {
            my $nested_err_msg  = $nested_reply->message();
            my $nested_err_code = $nested_reply->code();

            # error handling...
          }
        }

        return;
      }

      # error handling...

      return;
    }

    # reply handling...
  },
);

discard( [ $cb->( $reply, $err ) ] )

Flushes all the previously queued commands in a transaction and restores the connection state back to normal. Poof. Gone. 🧚

If WATCH was used, DISCARD unwatches all keys too.

watch( @keys [, $cb->( $reply, $err ) ] )

Marks the given keys to be watched for conditional execution of a transaction. πŸ‘€πŸ”­

unwatch( [ $cb->( $reply, $err ) ] )

Forget about all the watched keys.

πŸ’Œ SUBSCRIPTIONS πŸ’Œ

Okay bestie, listen up, this is the locked-in mode of the client. Once the client enters the subscribed state, it is not supposed to issue any other commands, except for additional SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE, PUNSUBSCRIBE and QUIT commands.

The detailed information about Redis Pub/Sub can be found here: http://redis.io/topics/pubsub

πŸŽ€ subscribe( @channels, ( $cb->( $msg, $channel ) | %cbs ) )

Subscribes the client to the specified channels. It's giving "let me in, let me in" energy.

Method can accept two callbacks: on_reply and on_message. The on_reply callback is called when subscription to all specified channels will be activated. In first argument to the callback is passed the number of channels we are currently subscribed. If subscription to specified channels was lost, the on_reply callback is called with the error object in the second argument. So check that second arg, bestie, it's not just decorative.

The on_message callback is called on every published message. If the subscribe method is called with one callback, this callback will be act as on_message callback.

$redis->subscribe( qw( foo bar ),
  { on_reply => sub {
      my $channels_num = shift;
      my $err          = shift;

      if ( defined $err ) {
        # error handling...

        return;
      }

      # reply handling...
    },

    on_message => sub {
      my $msg     = shift;
      my $channel = shift;

      # message handling...
    },
  }
);

$redis->subscribe( qw( foo bar ),
  sub {
    my $msg     = shift;
    my $channel = shift;

    # message handling...
  }
);

πŸ¦‹ psubscribe( @patterns, ( $cb->( $msg, $pattern, $channel ) | %cbs ) )

Subscribes the client to the given patterns. Wildcards, we love her. See subscribe() method for details.

$redis->psubscribe( qw( foo_* bar_* ),
  { on_reply => sub {
      my $channels_num = shift;
      my $err          = shift;

      if ( defined $err ) {
        # error handling...

        return;
      }

      # reply handling...
    },

    on_message => sub {
      my $msg     = shift;
      my $pattern = shift;
      my $channel = shift;

      # message handling...
    },
  }
);

$redis->psubscribe( qw( foo_* bar_* ),
  sub {
    my $msg     = shift;
    my $pattern = shift;
    my $channel = shift;

    # message handling...
  }
);

πŸ“£ publish( $channel, $message [, $cb->( $reply, $err ) ] )

Posts a message to the given channel. Scream it into the void, someone's subscribed and they WILL hear you.

πŸšͺ unsubscribe( [ @channels ] [, $cb->( $reply, $err ) ] )

Unsubscribes the client from the given channels, or from all of them if none is given. In first argument to the callback is passed the number of channels we are currently subscribed or zero if we were unsubscribed from all channels.

$redis->unsubscribe( qw( foo bar ),
  sub {
    my $channels_num = shift;
    my $err          = shift;

    if ( defined $err ) {
      # error handling...

      return;
    }

    # reply handling...
  }
);

🧚 punsubscribe( [ @patterns ] [, $cb->( $reply, $err ) ] )

Unsubscribes the client from the given patterns, or from all of them if none is given. See unsubscribe() method for details.

$redis->punsubscribe( qw( foo_* bar_* ),
  sub {
    my $channels_num = shift;
    my $err          = shift;

    if ( defined $err ) {
      # error handling...

      return;
    }

    # reply handling...
  }
);

πŸ”Œ CONNECTION VIA UNIX-SOCKET πŸ”Œ

Redis 2.2 and higher support connection via UNIX domain socket.</purl> 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. Yes, the port param is a path here. It's unhinged but it works, iykyk.

my $redis = AnyEvent::RipeRedis->new(
  host => 'unix/',
  port => '/tmp/redis.sock',
);

πŸŒ™ LUA SCRIPTS EXECUTION πŸŒ™

Redis 2.6 and higher support execution of Lua scripts on the server side. To execute a Lua script you can send one of the commands EVAL or EVALSHA, or use the special method eval_cached().

πŸ’« eval_cached( $script, $keys_num [, @keys ] [, @args ] [, $cb->( $reply, $err ) ] ] );

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 E_NO_SCRIPT error will be returned, the client send the EVAL command. Optimistic queen behavior, honestly.

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',
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      # error handling...

      return;
    }

    foreach my $value ( @{$reply}  ) {
      print "$value\n";
    }
  }
);
Be care, passing a different Lua scripts to eval_cached() method every time cause memory leaks. πŸ’€ Not a vibe. Reuse your scripts, bestie.

If Lua script returns multi-bulk reply with at least one error reply, to the callback will be passed error object, and the reply will be contain nested error objects.

$redis->eval_cached( "return { 'foo', redis.error_reply( 'Error.' ) }", 0,
  sub {
    my $reply = shift;
    my $err   = shift;

    if ( defined $err ) {
      my $err_msg  = $err->message;
      my $err_code = $err->code;

      if ( defined $reply ) {
        foreach my $nested_reply ( @{$reply} ) {
          if ( ref($nested_reply) eq 'AnyEvent::RipeRedis::Error' ) {
            my $nested_err_msg  = $nested_reply->message();
            my $nested_err_code = $nested_reply->code();

            # error handling...
          }
        }
      }

      # error handling...

      return;
    }

    # reply handling...
  }
);

🚨 ERROR CODES 🚨

Every error object, passed to callback, contain error code, which can be used for programmatic handling of errors. AnyEvent::RipeRedis provides constants for error codes. They can be imported and used in expressions. Import them, don't be out here comparing raw strings like a menace.

use AnyEvent::RipeRedis qw( :err_codes );
  • E_CANT_CONN β€” Can't connect to the server. All operations were aborted. πŸ’€
  • E_LOADING_DATASET β€” Redis is loading the dataset in memory.
  • E_IO β€” Input/Output operation error. The connection to the Redis server was closed and all operations were aborted.
  • E_CONN_CLOSED_BY_REMOTE_HOST β€” The connection closed by remote host. All operations were aborted.
  • E_CONN_CLOSED_BY_CLIENT β€” Connection closed by client prematurely. Uncompleted operations were aborted.
  • E_NO_CONN β€” No connection to the Redis server. Connection was lost by any reason on previous operation.
  • E_OPRN_ERROR β€” Operation error. For example, wrong number of arguments for a command.
  • E_UNEXPECTED_DATA β€” The client received unexpected reply from the server. The connection to the Redis server was closed and all operations were aborted.
  • E_READ_TIMEDOUT β€” Read timed out. The connection to the Redis server was closed and all operations were aborted.

Error codes available since Redis 2.6.

  • E_NO_SCRIPT β€” No matching script. Use the EVAL command.
  • E_BUSY β€” Redis is busy running a script. You can only call SCRIPT KILL or SHUTDOWN NOSAVE.
  • E_NOT_BUSY β€” No scripts in execution right now.
  • E_MASTER_DOWN β€” Link with MASTER is down and slave-serve-stale-data is set to 'no'.
  • E_MISCONF β€” 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.
  • E_READONLY β€” You can't write against a read only slave.
  • E_OOM β€” Command not allowed when used memory > 'maxmemory'.
  • E_EXEC_ABORT β€” Transaction discarded because of previous errors.

Error codes available since Redis 2.8.

  • E_NO_AUTH β€” Authentication required.
  • E_WRONG_TYPE β€” Operation against a key holding the wrong kind of value.
  • E_NO_REPLICAS β€” Not enough good slaves to write.
  • E_BUSY_KEY β€” Target key name already exists.

Error codes available since Redis 3.0.

  • E_CROSS_SLOT β€” Keys in request don't hash to the same slot.
  • E_TRY_AGAIN β€” Multiple keys request during rehashing of slot.
  • E_ASK β€” Redirection required. For more information see: http://redis.io/topics/cluster-spec
  • E_MOVED β€” Redirection required. For more information see: http://redis.io/topics/cluster-spec
  • E_CLUSTER_DOWN β€” The cluster is down or hash slot not served.

πŸ‘‹ DISCONNECTION πŸ‘‹

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::RipeRedis object, but in this case the client object is destroyed without calling any callbacks, including the on_disconnect callback, to avoid an unexpected behavior.

Just so we're clear on that third one: ghost it and it goes poof with zero callbacks. No goodbye text, no nothing. πŸ«₯

🫧 disconnect()

The method for synchronous disconnection. All uncompleted operations will be aborted.

πŸ•ŠοΈ quit( [ $cb->( $reply, $err ) ] )

The method for asynchronous disconnection.


✨ OTHER METHODS ✨

πŸ“Š info( [ $section ] [, $cb->( $reply, $err ) ] )

Gets and parses information and statistics about the server. The result is passed to callback as a hash reference.

More information about INFO command can be found here: http://redis.io/commands/info

🏠 host()

Gets current host of the client.

πŸ”’ port()

Gets current port of the client.

πŸ—‚οΈ select( $index, [, $cb->( $reply, $err ) ] )

Selects the database by numeric index.

πŸ’Ύ database()

Gets selected database index.

🌈 utf8( [ $boolean ] )

Enables or disables UTF-8 mode.

⏳ connection_timeout( [ $fractional_seconds ] )

Gets or sets the connection_timeout of the client. The undef value resets the connection_timeout to default value.

βŒ› read_timeout( [ $fractional_seconds ] )

Gets or sets the read_timeout of the client.

πŸ”„ reconnect( [ $boolean ] )

Enables or disables reconnection mode of the client.

⏱️ reconnect_interval( [ $fractional_seconds ] )

Gets or sets reconnect_interval of the client.

πŸ’– on_connect( [ $callback ] )

Gets or sets the on_connect callback.

πŸ’” on_disconnect( [ $callback ] )

Gets or sets the on_disconnect callback.

😭 on_error( [ $callback ] )

Gets or sets the on_error callback.

🌈 SEE ALSO

okay bestie, if you wanna go deeper (and you know you do πŸ’…), go check these out:

  • AnyEvent::RipeRedis::Cluster β€” the cluster sibling, she's giving main character energy too ✨
  • AnyEvent β€” the whole reason this vibe exists, the event loop queen πŸ‘‘
  • Redis::hiredis β€” the C-level speed demon underneath, no cap πŸ”₯
  • Redis β€” the classic Perl client, an icon, a legend πŸŽ€
  • RedisDB β€” another one, go look, fr fr πŸ¦‹

πŸ’– AUTHOR

Eugene Ponizovsky, <ponizovsky@gmail.com> β€” he literally built this, periodt 🫢

Sponsored by SMS Online, <dev.opensource@sms-online.com> β€” shoutout to the sponsors, they ate πŸ’œ

🌸 Special thanks

like, these people deserve their flowers, not me being dramatic, it's just true:

  • Alexey Shrub
  • Vadim Vlasov
  • Konstantin Uvarin
  • Ivan Kruglov

Copyright (c) 2012-2021, Eugene Ponizovsky, SMS Online. All rights reserved. πŸ’–

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

bestie this is the legal bit and it's important β€” free software, same terms as Perl, keep the copyright notice, okay? don't be that person πŸ™ˆ

and that's a wrap on the whole page, my love 🌈✨ you made it to the end, which is honestly iconic behavior. this was the AnyEvent::RipeRedis(3pm) manpage from Perl v5.40.1, dated 2025-03-04 β€” go forth and cache responsibly, and remember: the connection is yours, close it when you're done πŸŽ€πŸ’…πŸ’œ

πŸ“¦ where this page comes from