Redis(3pm)

๐Ÿ“ฆ
version 2.000 ยท 7 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

๐Ÿ’– Redis(3pm) โ€” the Perl binding for Redis, bestie edition ๐Ÿ’–

okay so like. you want to talk to Redis. from Perl. and you want it to be easy. that's literally this module, Redis, and it's documented as a 3pm man page (Perl module docs, you know the vibe). let's get into it ๐Ÿซถ


โœจ NAME โœจ

Redis โ€” Perl binding for Redis database. no cap, that's the whole pitch ๐Ÿ’…


๐ŸŒธ VERSION ๐ŸŒธ

version 2.000 โ€” that's the version, periodt.


๐ŸŽ€ SYNOPSIS ๐ŸŽ€

okay bestie, this is the part where we just vibe and look at all the ways you can spin up a connection. everything here is copy-paste-able, go wild:

## Defaults to $ENV{REDIS_SERVER} or 127.0.0.1:6379
my $redis = Redis->new;

my $redis = Redis->new(server => 'redis.example.com:8080');

## Set the connection name (requires Redis 2.6.9)
my $redis = Redis->new(
  server => 'redis.example.com:8080',
  name => 'my_connection_name',
);
my $generation = 0;
my $redis = Redis->new(
  server => 'redis.example.com:8080',
  name => sub { "cache-$$-".++$generation },
);

## Use UNIX domain socket
my $redis = Redis->new(sock => '/path/to/socket');

## Connect to Redis over a secure SSL/TLS channel.  See
## IO::Socket::SSL documentation for more information
## about SSL_verify_mode parameter.
my $redis = Redis->new(
    server => 'redis.tls.example.com:8080',
    ssl => 1,
    SSL_verify_mode => SSL_VERIFY_PEER,
);

## Enable auto-reconnect
## Try to reconnect every 1s up to 60 seconds until success
## Die if you can't after that
my $redis = Redis->new(reconnect => 60, every => 1_000_000);

## Try each 100ms up to 2 seconds (every is in microseconds)
my $redis = Redis->new(reconnect => 2, every => 100_000);

## Enable connection timeout (in seconds)
my $redis = Redis->new(cnx_timeout => 60);

## Enable read timeout (in seconds)
my $redis = Redis->new(read_timeout => 0.5);

## Enable write timeout (in seconds)
my $redis = Redis->new(write_timeout => 1.2);

## Connect via a list of Sentinels to a given service
my $redis = Redis->new(sentinels => [ '127.0.0.1:12345' ], service => 'mymaster');

## Same, but with connection, read and write timeout on the sentinel hosts
my $redis = Redis->new( sentinels => [ '127.0.0.1:12345' ], service => 'mymaster',
                        sentinels_cnx_timeout => 0.1,
                        sentinels_read_timeout => 1,
                        sentinels_write_timeout => 1,
                      );

## Use all the regular Redis commands, they all accept a list of
## arguments
## See https://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
$redis->wait_one_response();

## 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');

like, look at all of that. connection names, sockets, TLS, auto-reconnect, timeouts, sentinels, pipelining, pub/sub โ€” it's giving range ๐Ÿ”ฅ


๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Pure perl bindings for <https://redis.io/>. pure perl, no compiled C extension nonsense, we love that for us ๐Ÿ’–

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". translation: the docs show you what's been battle-tested, but basically any other command is gonna work anyway because the protocol just hands over enough info, and "AUTOLOAD" picks up the slack. iconic behavior honestly โœจ


๐ŸŒˆ PIPELINING ๐ŸŒˆ

so normally? you run a command, you sit there waiting for the response. very "watching paint dry" energy. but if you're firing off a lot of requests, it's way more efficient to do the thing Redis calls pipelining: yeet a bunch of commands at Redis without waiting for any responses, then collect all the responses as they come back. main character efficiency ๐Ÿ’…

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 is called on the same connection
  • A pub/sub subscription command (one of "subscribe", "unsubscribe", "psubscribe", or "punsubscribe") is about to be called on the same connection.
  • One of "wait_all_responses" or "wait_one_response" methods 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".

Note the contrast with synchronous commands, which throw an exception on receipt of an error reply, or return a non-error reply directly. so like, pipelined = errors get handed to you, sync = errors get thrown at you. different vibes, both valid ๐Ÿซถ

The fact that pipelined commands never throw an exception can be particularly useful for Redis transactions; see "exec". ๐Ÿ‘‘


๐Ÿงš ENCODING ๐Ÿงš

There is no encoding feature anymore, it has been deprecated and finally removed. This module consider that any data sent to the Redis server is a binary data. And it doesn't do anything when getting data from the Redis server.

So, if you are working with character strings, you should pre-encode or post-decode it if needed !

okay so real talk bestie: the encoding feature is gone. deprecated, then fully removed, RIP ๐Ÿ’€. this module treats literally everything you send to Redis as binary data, and it does nothing to data coming back from Redis. so if you're dealing with character strings, that's on you โ€” pre-encode on the way in, post-decode on the way out, fr fr.

๐ŸŽ€ CONSTRUCTOR ๐ŸŽ€

okay bestie, this is where the magic literally begins. this is how you make a Redis object. look at all these flavours:

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( server => '192.168.0.1:6379', ssl => 1, SSL_verify_mode => SSL_VERIFY_PEER );
my $r = Redis->new( sock => '/path/to/sock' );
my $r = Redis->new( reconnect => 60, every => 5000 );
my $r = Redis->new( password => 'boo' );
my $r = Redis->new( on_connect => sub { my ($redis) = @_; ... } );
my $r = Redis->new( name => 'my_connection_name' );
my $r = Redis->new( name => sub { "cache-for-$$" });

my $redis = Redis->new(sentinels => [ '127.0.0.1:12345', '127.0.0.1:23456' ],
                       service => 'mymaster');

## Connect via a list of Sentinels to a given service
my $redis = Redis->new(sentinels => [ '127.0.0.1:12345' ], service => 'mymaster');

## Same, but with connection, read and write timeout on the sentinel hosts
my $redis = Redis->new( sentinels => [ '127.0.0.1:12345' ], service => 'mymaster',
                        sentinels_cnx_timeout => 0.1,
                        sentinels_read_timeout => 1,
                        sentinels_write_timeout => 1,
                      );

pick your fighter. ๐Ÿ’…

โœจ new โœจ

๐Ÿ–ฅ๏ธ "server"

the "server" param is like, which Redis are we even talking to? it's TCP, and you write it in 'IP:PORT' format. if you don't pass "server" at all, we'll go looking for the "REDIS_SERVER" environment variable. and if that's not there either, we just default to '127.0.0.1:6379'. slay, sensible defaults.

OR โ€” plot twist โ€” you can use the "sock" parameter to hand over the path of the UNIX domain socket your Redis server is vibing on.

OR โ€” second plot twist โ€” you can use "sentinels" + "service" to give a list of sentinels to hit up and try to get the address of the service name you want. heads up: "sentinels" has to be an ArrayRef and "service" has to be an Str. no cap.

and yes, "REDIS_SERVER" works for UNIX domain sockets too ๐Ÿซถ these are the formats we accept:

  • /path/to/sock
  • unix:/path/to/sock
  • 127.0.0.1:11011
  • tcp:127.0.0.1:11011

๐Ÿ” "reconnect", "every"

setting "reconnect" turns on auto-reconnection mode. if we can't connect to the Redis server, or if a network write fails, we go into retry mode. we'll try a fresh connection every "every" microseconds (default is 1 ms), for up to "reconnect" seconds. obsessed with resilience honestly.

โš ๏ธ but know this: read errors will always throw an exception, and they won't trigger a retry until the next command gets sent. that's just how it is, bestie.

and if we still can't re-establish a connection after "reconnect" seconds? exception. thrown. periodt.

๐Ÿ›ก๏ธ "conservative_reconnect"

"conservative_reconnect" is the safe-girl option โ€” it makes sure reconnection only gets attempted when there's no pending command in flight. here's the scenario that'll ruin your day: you're doing $redis->incr('key'), the server fully understood and processed the command, but the network drops right before the server replies. so the command did happen, but the client has no idea. if reconnect is enabled, the Redis client will reconnect and send that incr command again. and if it succeeds, congratulations, your key got incremented twice. ๐Ÿ˜ญ

to dodge that whole situation, set "conservative_reconnect" to a true value. then the client only reconnects if no request is pending. otherwise it dies with this message: reconnect disabled while responses are pending and safe reconnect mode enabled. blunt, but honest.

โฑ๏ธ "cnx_timeout"

"cnx_timeout" turns on connection timeout. the Redis client will wait at most that many seconds (fractional is fine, she's flexible) before giving up on connecting to a server.

๐Ÿ“ก "sentinels_cnx_timeout"

"sentinels_cnx_timeout" is the same deal but for sentinel connections. when you're using the sentinels feature, the Redis client waits at most that many seconds (fractional totally fine) before giving up on connecting to a sentinel. Default: 0.1

๐Ÿ“– "read_timeout"

"read_timeout" enables read timeout. the Redis client waits at most that many seconds (fractional, yes) before giving up when reading from the server.

๐Ÿ“ก๐Ÿ“– "sentinels_read_timeout"

"sentinels_read_timeout" is the sentinel version. when using the sentinels feature, the client waits at most that many seconds (fractional, bestie) before giving up when reading from a sentinel server. Default: 1

โœ๏ธ "write_timeout"

"write_timeout" enables write timeout. the Redis client waits at most that many seconds (fractional, obviously) before giving up when reading from the server.

๐Ÿ“กโœ๏ธ "sentinels_write_timeout"

"sentinels_write_timeout" โ€” sentinel edition. when using the sentinels feature, the client waits at most that many seconds (fractional!) before giving up when reading from a sentinel server. Default: 1

๐Ÿ”‘ "password"

if your Redis server is like "who even are you", use the "password" attribute. after every established connection (whether it's the first one or a reconnect), the Redis AUTH command gets sent to the server. and if the password is wrong? exception thrown, and reconnect gets disabled. no second chances with bad credentials, that's the vibe.

๐ŸŽฃ "on_connect"

you can also hand over a code reference that runs immediately after each successful connection. the "on_connect" attribute is where that code ref lives, and it gets called with the Redis object as its first parameter.

๐Ÿšซ "no_auto_connect_on_new"

give "no_auto_connect_on_new" and new won't implicitly call $obj->connect for you โ€” you'll have to do it yourself. why would you want that? it's lowkey perfect for measuring how long connection setup actually takes, so you can configure "cnx_timeout" like a responsible queen.

๐Ÿšซ๐Ÿ“‹ "no_sentinels_list_update"

you can also pass "no_sentinels_list_update". by default (i.e. without this option), whenever we successfully contact a sentinel server, the Redis client asks it for the list of sentinels known for that service, and merges it into its own list of sentinels (that's the "sentinels" attribute). want none of that? set "no_sentinels_list_update" to a true value and it stops.

๐Ÿท๏ธ "name"

you can set a name for each connection and honestly it's so useful for debugging, via the "CLIENT LIST" command. use the "name" parameter. it takes either a scalar value or a CodeRef โ€” if it's a CodeRef, it gets called after each connection with the Redis object, and it should return the connection name to use. if it returns an undefined value, Redis just won't set the connection name. simple as.

โš ๏ธ okay important: there are restrictions on the name you can set, and the biggest one is no spaces. the CLIENT SETNAME documentation (https://redis.io/commands/client-setname) has all the juicy details.

this feature is safe with all versions of Redis servers, but if "CLIENT SETNAME" support isn't available (that's Redis servers 2.6.9 and above only, bestie), the name parameter just gets ignored. no drama.

๐Ÿ”’ "ssl"

want to connect to Redis over SSL/TLS? set this flag โ€” but only if your target Redis server or cluster is actually set up to support SSL/TLS. it requires IO::Socket::SSL to be installed on the client. and it's off by default.

๐Ÿ” "SSL_verify_mode"

this one applies when the "ssl" flag is set. it sets the verification mode for the peer certificate. it's compatible with the parameter of the same name in IO::Socket::SSL. cute and consistent.

๐Ÿ› "debug"

the "debug" parameter sends debug info to STDERR, including all the interactions with the server. you can also flip debug on with the "REDIS_DEBUG" environment variable. peak transparency honestly.


๐Ÿ”Œ CONNECTION HANDLING ๐Ÿ”Œ

connect

$r->connect;

connects to the Redis server. this already happens by default when the object is constructed with new(), unless no_auto_connect_on_new has been set. go peep that option in the new() constructor section above. ๐Ÿ‘‘

quit

$r->quit;

closes the connection to the server. heads up bestie: the quit method does not support pipelined operation.

ping

$r->ping || die "no server?";

also important: the ping method does not support pipelined operation either.


๐Ÿ“ฌ PIPELINE MANAGEMENT ๐Ÿ“ฌ

wait_all_responses

waits until all pending pipelined responses have been received, and invokes the pipeline callback for each one. see "PIPELINING". ๐ŸŒธ

wait_one_response

waits until the first pending pipelined response has been received, and invokes its callback. see "PIPELINING". one at a time, methodically, we love a patient icon. โœจ

๐Ÿ’Œ PUBLISH/SUBSCRIBE COMMANDS ๐Ÿ’Œ

Okay so 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. That's the rule, bestie. ๐Ÿ’…

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. Do not make one object do both, it's giving chaos. ๐Ÿซถ

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 <https://redis.io/topics/pubsub> for more information about the messages you will receive on your callbacks after each subscribe, unsubscribe, psubscribe and punsubscribe. โœจ

publish

$r->publish($topic, $message);

Publishes the $message to the $topic. Drop it like it's hot. ๐Ÿ”ฅ

subscribe

$r->subscribe(
    @topics_to_subscribe_to,
    my $savecallback = sub {
      my ($message, $topic, $subscribed_topic) = @_;
      ...
    },
);

Subscribe one or more topics. Messages published into one of them will be received by Redis, and the specified callback will be executed. Slay. ๐Ÿ’–

unsubscribe

$r->unsubscribe(@topic_list, $savecallback);

Stops receiving messages via $savecallback for all the topics in @topic_list.

WARNING: it is important that you give the same callback that you used for subscription. The value of the CodeRef must be the same, as this is how internally the code identifies it. No cap, if you pass a different one it won't work. ๐Ÿ˜ญ

psubscribe

my @topic_matches = ('prefix1.*', 'prefix2.*');
$r->psubscribe(@topic_matches, my $savecallback = sub { my ($m, $t, $s) = @_; ... });

Subscribes a pattern of topics. All messages to topics that match the pattern will be delivered to the callback. Pattern matching? We love to see it. ๐ŸŒธ

punsubscribe

my @topic_matches = ('prefix1.*', 'prefix2.*');
$r->punsubscribe(@topic_matches, $savecallback);

Stops receiving messages via $savecallback for all the topics pattern matches in @topic_list.

WARNING: it is important that you give the same callback that you used for subscription. The value of the CodeRef must be the same, as this is how internally the code identifies it. Yes bestie, same energy as unsubscribe. ๐Ÿ’…

is_subscriber

if ($r->is_subscriber) { say "We are in Pub/Sub mode!" }

Returns true if we are in Pub/Sub mode. Vibe check passed. โœ…

wait_for_messages

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. It's giving patient queen. ๐Ÿ‘‘

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 amount of seconds without a single notification.

Please note that the timeout is not a commitment to return control to the caller at most each timeout seconds, but more an idle timeout, where 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. So don't expect it to be clockwork, okay? ๐Ÿ•ฐ๏ธ

The wait_for_messages call returns the number of messages processed during the run.


๐Ÿšจ IMPORTANT NOTES ON METHODS ๐Ÿšจ

methods that return multiple values

When a method returns more than one value, it checks the context and returns either a list of values or an ArrayRef. Context is everything, bestie. ๐Ÿ’œ

transaction-handling methods

Warning: the behaviour of the TRANSACTIONS commands when combined with pipelining is still under discussion, and you should NOT use them at the same time just now. I'm serious, don't do it. ๐Ÿ’€

You can follow the discussion to see the open issues with this <https://github.com/PerlRedis/perl-redis/issues/17>.

exec

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. So you get the tea on every command. ๐Ÿต

keys

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. Sneaky, but now you know. ๐Ÿ™ˆ

hashes

Hashes in Redis cannot be nested as in perl, if you want to store a nested hash, you need to serialize the hash first. If you want to have a named hash, you can use Redis-hashes. You will find an example in the tests of this module t/01-basic.t. Go look, it's there. ๐ŸŽ€

eval

Note that this command sends the Lua script every time you call it. See evalsha and script_load for an alternative. Efficiency who? We know her. โœจ

info

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. Iconic behaviour, honestly. ๐Ÿ‘‘


๐Ÿ—๏ธ KEYS ๐Ÿ—๏ธ

del

$r->del(key [key ...])

Delete a key (see <https://redis.io/commands/del>)

dump

$r->dump(key)

Return a serialized version of the value stored at the specified key. (see <https://redis.io/commands/dump>)

exists

$r->exists(key)

Determine if a key exists (see <https://redis.io/commands/exists>)

expire

$r->expire(key, seconds)

Set a key's time to live in seconds (see <https://redis.io/commands/expire>)

expireat

$r->expireat(key, timestamp)

Set the expiration for a key as a UNIX timestamp (see <https://redis.io/commands/expireat>)

keys

$r->keys(pattern)

Find all keys matching the given pattern (see <https://redis.io/commands/keys>)

migrate

$r->migrate(host, port, key, destination-db, timeout, [COPY], [REPLACE])

Atomically transfer a key from a Redis instance to another one. (see <https://redis.io/commands/migrate>)

move

$r->move(key, db)

Move a key to another database (see <https://redis.io/commands/move>)

object

$r->object(subcommand, [arguments [arguments ...]])

Inspect the internals of Redis objects (see <https://redis.io/commands/object>)

persist

$r->persist(key)

Remove the expiration from a key (see <https://redis.io/commands/persist>)

pexpire

$r->pexpire(key, milliseconds)

Set a key's time to live in milliseconds (see <https://redis.io/commands/pexpire>)

pexpireat

$r->pexpireat(key, milliseconds-timestamp)

Set the expiration for a key as a UNIX timestamp specified in milliseconds (see <https://redis.io/commands/pexpireat>)

pttl

$r->pttl(key)

Get the time to live for a key in milliseconds (see <https://redis.io/commands/pttl>)

randomkey

$r->randomkey()

Return a random key from the keyspace (see <https://redis.io/commands/randomkey>)

rename

$r->rename(key, newkey)

Rename a key (see <https://redis.io/commands/rename>)

renamenx

$r->renamenx(key, newkey)

Rename a key, only if the new key does not exist (see <https://redis.io/commands/renamenx>)

restore

$r->restore(key, ttl, serialized-value)

Create a key using the provided serialized value, previously obtained using DUMP. (see <https://redis.io/commands/restore>)

scan

$r->scan(cursor, [MATCH pattern], [COUNT count])

Incrementally iterate the keys space (see <https://redis.io/commands/scan>)

sort

$r->sort(key, [BY pattern], [LIMIT offset count], [GET pattern [GET pattern ...]], [ASC|DESC], [ALPHA], [STORE destination])

Sort the elements in a list, set or sorted set (see <https://redis.io/commands/sort>)

ttl

$r->ttl(key)

Get the time to live for a key (see <https://redis.io/commands/ttl>)

type

$r->type(key)

Determine the type stored at key (see <https://redis.io/commands/type>)

๐Ÿ’– STRINGS ๐Ÿ’–

okay so bestie, strings are literally the bread and butter of Redis, and these commands are your new besties for storing and messing with text and numbers. let's get into it. ๐Ÿซถ


append ๐Ÿงต

$r->append(key, value)

appends value to whatever's already in key. it's giving "add to the end" energy. (see https://redis.io/commands/append)

bitcount ๐Ÿ”ข

$r->bitcount(key, [start end])

counts how many bits are set to 1 in a string, no cap. (see https://redis.io/commands/bitcount)

bitop โšก

$r->bitop(operation, destkey, key [key ...])

does bitwise operations between strings, periodt. (see https://redis.io/commands/bitop)

bitpos ๐Ÿ”

$r->bitpos(key, bit, [start], [end])

finds the first bit that's either set or clear in a string, iykyk. (see https://redis.io/commands/bitpos)

blpop ๐Ÿ›‘

$r->blpop(key [key ...], timeout)

removes and gets the first element in a list, or blocks until one shows up. it's giving main character energy waiting for its moment. (see https://redis.io/commands/blpop)

brpop ๐Ÿ›‘

$r->brpop(key [key ...], timeout)

removes and gets the last element in a list, or blocks until one is available. patient queen. (see https://redis.io/commands/brpop)

brpoplpush ๐Ÿ”„

$r->brpoplpush(source, destination, timeout)

pops a value from a list, pushes it to another list, and returns it; or blocks until one is available. it's a whole journey. (see https://redis.io/commands/brpoplpush)

decr ๐Ÿ“‰

$r->decr(key)

decrements the integer value of a key by one. math but make it fashion. (see https://redis.io/commands/decr)

decrby ๐Ÿ“‰

$r->decrby(key, decrement)

decrements the integer value of a key by the number you give it. (see https://redis.io/commands/decrby)

get ๐ŸŽ

$r->get(key)

gets the value of a key. simple as that. (see https://redis.io/commands/get)

getbit ๐Ÿ”น

$r->getbit(key, offset)

returns the bit value at offset in the string stored at key. (see https://redis.io/commands/getbit)

getrange โœ‚๏ธ

$r->getrange(key, start, end)

gets a substring of the string stored at a key. slice it. (see https://redis.io/commands/getrange)

getset ๐Ÿ”

$r->getset(key, value)

sets the string value of a key and returns the old value. it's a glow-up with receipts. (see https://redis.io/commands/getset)

incr ๐Ÿ“ˆ

$r->incr(key)

increments the integer value of a key by one. +1 energy. (see https://redis.io/commands/incr)

incrby ๐Ÿ“ˆ

$r->incrby(key, increment)

increments the integer value of a key by the amount you specify. (see https://redis.io/commands/incrby)

incrbyfloat ๐Ÿงฎ

$r->incrbyfloat(key, increment)

increments the float value of a key by the given amount. decimals are valid. (see https://redis.io/commands/incrbyfloat)

mget ๐Ÿ“ฆ

$r->mget(key [key ...])

gets the values of all the keys you list. multitasking queen. (see https://redis.io/commands/mget)

mset ๐Ÿ“ฆ

$r->mset(key value [key value ...])

sets multiple keys to multiple values. bulk vibes. (see https://redis.io/commands/mset)

msetnx ๐Ÿ“ฆ

$r->msetnx(key value [key value ...])

sets multiple keys to multiple values, but only if none of the keys already exist. no takebacks. (see https://redis.io/commands/msetnx)

psetex โณ

$r->psetex(key, milliseconds, value)

sets the value and expiration in milliseconds of a key. precise. (see https://redis.io/commands/psetex)

set โœจ

$r->set(key, value, ['EX',  seconds], ['PX', milliseconds], ['NX'|'XX'])

sets the string value of a key. the classic. example:

$r->set('key', 'test', 'EX', 60, 'NX')

(see https://redis.io/commands/set)

setbit ๐Ÿ”ธ

$r->setbit(key, offset, value)

sets or clears the bit at offset in the string value stored at key. (see https://redis.io/commands/setbit)

setex โณ

$r->setex(key, seconds, value)

sets the value and expiration of a key. like a self-destructing message but for data. (see https://redis.io/commands/setex)

setnx ๐Ÿฅ‡

$r->setnx(key, value)

sets the value of a key, but only if the key doesn't already exist. first come, first served. (see https://redis.io/commands/setnx)

setrange โœ๏ธ

$r->setrange(key, offset, value)

overwrites part of a string at key starting at the specified offset. edit that text. (see https://redis.io/commands/setrange)

strlen ๐Ÿ“

$r->strlen(key)

gets the length of the value stored in a key. how long is it? very. (see https://redis.io/commands/strlen)


๐Ÿ’œ HASHES ๐Ÿ’œ

okay so hashes are like little dictionaries, and these commands are how you talk to them. let's go. ๐Ÿงš

hdel ๐Ÿ—‘๏ธ

$r->hdel(key, field [field ...])

deletes one or more hash fields. bye felicia. (see https://redis.io/commands/hdel)

hexists โ“

$r->hexists(key, field)

determines if a hash field exists. does it exist? maybe. (see https://redis.io/commands/hexists)

hget ๐Ÿ”

$r->hget(key, field)

gets the value of a hash field. (see https://redis.io/commands/hget)

hgetall ๐Ÿ“š

$r->hgetall(key)

gets all the fields and values in a hash. the whole tea. (see https://redis.io/commands/hgetall)

hincrby ๐Ÿ“ˆ

$r->hincrby(key, field, increment)

increments the integer value of a hash field by the given number. (see https://redis.io/commands/hincrby)

hincrbyfloat ๐Ÿงฎ

$r->hincrbyfloat(key, field, increment)

increments the float value of a hash field by the given amount. (see https://redis.io/commands/hincrbyfloat)

hkeys ๐Ÿ”‘

$r->hkeys(key)

gets all the fields in a hash. (see https://redis.io/commands/hkeys)

hlen ๐Ÿ“

$r->hlen(key)

gets the number of fields in a hash. (see https://redis.io/commands/hlen)

hmget ๐Ÿ“ฆ

$r->hmget(key, field [field ...])

gets the values of all the given hash fields. (see https://redis.io/commands/hmget)

hmset ๐Ÿ“ฆ

$r->hmset(key, field value [field value ...])

sets multiple hash fields to multiple values. (see https://redis.io/commands/hmset)

hscan ๐Ÿ”„

$r->hscan(key, cursor, [MATCH pattern], [COUNT count])

incrementally iterates hash fields and associated values. (see https://redis.io/commands/hscan)

hset โœจ

$r->hset(key, field, value)

sets the string value of a hash field. (see https://redis.io/commands/hset)

hsetnx ๐Ÿฅ‡

$r->hsetnx(key, field, value)

sets the value of a hash field, but only if the field doesn't already exist. (see https://redis.io/commands/hsetnx)

hvals ๐Ÿ’Ž

$r->hvals(key)

gets all the values in a hash. (see https://redis.io/commands/hvals)


๐Ÿ’™ SETS ๐Ÿ’™

sets are unordered collections of unique things, and these commands are the moment. ๐Ÿ’…

sadd ๐ŸŽ€

$r->sadd(key, member [member ...])

adds one or more members to a set. collect them all. (see https://redis.io/commands/sadd)

scard ๐Ÿ”ข

$r->scard(key)

gets the number of members in a set. (see https://redis.io/commands/scard)

sdiff โž–

$r->sdiff(key [key ...])

subtracts multiple sets. math but make it sets. (see https://redis.io/commands/sdiff)

sdiffstore ๐Ÿ’พ

$r->sdiffstore(destination, key [key ...])

subtracts multiple sets and stores the resulting set in a key. (see https://redis.io/commands/sdiffstore)

sinter ๐Ÿ”—

$r->sinter(key [key ...])

intersects multiple sets. the overlap. (see https://redis.io/commands/sinter)

sinterstore ๐Ÿ’พ

$r->sinterstore(destination, key [key ...])

intersects multiple sets and stores the resulting set in a key. (see https://redis.io/commands/sinterstore)

sismember โ“

$r->sismember(key, member)

determines if a given value is a member of a set. are you in or out? (see https://redis.io/commands/sismember)

smembers ๐Ÿ‘ฏ

$r->smembers(key)

gets all the members in a set. the whole squad. (see https://redis.io/commands/smembers)

smove ๐Ÿšš

$r->smove(source, destination, member)

moves a member from one set to another. relocation. (see https://redis.io/commands/smove)

spop ๐ŸŽฒ

$r->spop(key)

removes and returns a random member from a set. surprise! (see https://redis.io/commands/spop)

srandmember ๐ŸŽฒ

$r->srandmember(key, [count])

gets one or multiple random members from a set. (see https://redis.io/commands/srandmember)

srem ๐Ÿ—‘๏ธ

$r->srem(key, member [member ...])

removes one or more members from a set. (see https://redis.io/commands/srem)

sscan ๐Ÿ”„

$r->sscan(key, cursor, [MATCH pattern], [COUNT count])

incrementally iterates Set elements. (see https://redis.io/commands/sscan)

sunion โž•

$r->sunion(key [key ...])

adds multiple sets. (see https://redis.io/commands/sunion)

sunionstore ๐Ÿ’พ

$r->sunionstore(destination, key [key ...])

adds multiple sets and stores the resulting set in a key. (see https://redis.io/commands/sunionstore)

๐Ÿ“ SORTED SETS ๐Ÿ“

okay bestie, sorted sets are literally the moment. they keep everything in order by score and it's giving โœจorganizedโœจ. let's get into it ๐Ÿ’…

zadd

$r->zadd(key, score member [score member ...])

Adds one or more members to a sorted set, or updates its score if it already exists. (see https://redis.io/commands/zadd) โ€” no cap, this is the glow-up command ๐Ÿ’–

zcard

$r->zcard(key)

Get the number of members in a sorted set. (see https://redis.io/commands/zcard) โ€” it's giving headcount energy ๐Ÿ‘‘

zcount

$r->zcount(key, min, max)

Count the members in a sorted set with scores within the given values. (see https://redis.io/commands/zcount) โ€” lowkey a vibe check for scores ๐Ÿ”ฅ

zincrby

$r->zincrby(key, increment, member)

Increment the score of a member in a sorted set. (see https://redis.io/commands/zincrby) โ€” we love a little boost, fr fr ๐Ÿ’…

zinterstore

$r->zinterstore(destination, numkeys, key [key ...], [WEIGHTS weight [weight ...]], [AGGREGATE SUM|MIN|MAX])

Intersect multiple sorted sets and store the resulting sorted set in a new key. (see https://redis.io/commands/zinterstore) โ€” intersection slay โœจ

zlexcount

$r->zlexcount(key, min, max)

Count the number of members in a sorted set between a given lexicographical range. (see https://redis.io/commands/zlexcount) โ€” lexicographical? we love a fancy word ๐ŸŽ€

zrange

$r->zrange(key, start, stop, [WITHSCORES])

Return a range of members in a sorted set, by index. (see https://redis.io/commands/zrange) โ€” range queen behavior ๐Ÿ‘‘

zrangebylex

$r->zrangebylex(key, min, max, [LIMIT offset count])

Return a range of members in a sorted set, by lexicographical range. (see https://redis.io/commands/zrangebylex) โ€” alphabetically iconic ๐Ÿ’–

zrangebyscore

$r->zrangebyscore(key, min, max, [WITHSCORES], [LIMIT offset count])

Return a range of members in a sorted set, by score. (see https://redis.io/commands/zrangebyscore) โ€” score-based and stunning ๐Ÿ”ฅ

zrank

$r->zrank(key, member)

Determine the index of a member in a sorted set. (see https://redis.io/commands/zrank) โ€” finding your place in the lineup, periodt ๐Ÿ’…

zrem

$r->zrem(key, member [member ...])

Remove one or more members from a sorted set. (see https://redis.io/commands/zrem) โ€” bye bestie, we won't miss you ๐Ÿ˜ญ

zremrangebylex

$r->zremrangebylex(key, min, max)

Remove all members in a sorted set between the given lexicographical range. (see https://redis.io/commands/zremrangebylex) โ€” clearing out the alphabet soup ๐Ÿงš

zremrangebyrank

$r->zremrangebyrank(key, start, stop)

Remove all members in a sorted set within the given indexes. (see https://redis.io/commands/zremrangebyrank) โ€” index-based removal, no cap ๐Ÿ—‘๏ธ

zremrangebyscore

$r->zremrangebyscore(key, min, max)

Remove all members in a sorted set within the given scores. (see https://redis.io/commands/zremrangebyscore) โ€” score range cleanup, we love a tidy vibe โœจ

zrevrange

$r->zrevrange(key, start, stop, [WITHSCORES])

Return a range of members in a sorted set, by index, with scores ordered from high to low. (see https://redis.io/commands/zrevrange) โ€” reverse it, flip it, slay it ๐Ÿ’…

zrevrangebylex

$r->zrevrangebylex(key, max, min, [LIMIT offset count])

Return a range of members in a sorted set, by lexicographical range, ordered from higher to lower strings. (see https://redis.io/commands/zrevrangebylex) โ€” lex order but backwards, iconic ๐ŸŒˆ

zrevrangebyscore

$r->zrevrangebyscore(key, max, min, [WITHSCORES], [LIMIT offset count])

Return a range of members in a sorted set, by score, with scores ordered from high to low. (see https://redis.io/commands/zrevrangebyscore) โ€” high score first, main character energy ๐Ÿ‘‘

zrevrank

$r->zrevrank(key, member)

Determine the index of a member in a sorted set, with scores ordered from high to low. (see https://redis.io/commands/zrevrank) โ€” rank reveal but reversed, obsessed ๐Ÿ’–

zscan

$r->zscan(key, cursor, [MATCH pattern], [COUNT count])

Incrementally iterate sorted sets elements and associated scores. (see https://redis.io/commands/zscan) โ€” slow and steady wins the scan ๐Ÿข

zscore

$r->zscore(key, member)

Get the score associated with the given member in a sorted set. (see https://redis.io/commands/zscore) โ€” just the score, bestie, no extras ๐Ÿ’…

zunionstore

$r->zunionstore(destination, numkeys, key [key ...], [WEIGHTS weight [weight ...]], [AGGREGATE SUM|MIN|MAX])

Add multiple sorted sets and store the resulting sorted set in a new key. (see https://redis.io/commands/zunionstore) โ€” union? more like unite and slay โœจ


๐ŸŒˆ HYPERLOGLOG ๐ŸŒˆ

hyperloglog is giving "I count things but approximately" and honestly? same. let's go ๐Ÿฆ‹

pfadd

$r->pfadd(key, element [element ...])

Adds the specified elements to the specified HyperLogLog. (see https://redis.io/commands/pfadd) โ€” adding elements, no biggie ๐Ÿ’–

pfcount

$r->pfcount(key [key ...])

Return the approximated cardinality of the set(s) observed by the HyperLogLog at key(s). (see https://redis.io/commands/pfcount) โ€” approximate but make it fashion ๐Ÿ’…

pfmerge

$r->pfmerge(destkey, sourcekey [sourcekey ...])

Merge N different HyperLogLogs into a single one. (see https://redis.io/commands/pfmerge) โ€” merge them all, it's a crossover event ๐Ÿ”ฅ


๐ŸŒŸ PUB/SUB ๐ŸŒŸ

pub/sub is the group chat of Redis, fr fr. everyone gets the message. ๐Ÿ’ฌ

pubsub

$r->pubsub(subcommand, [argument [argument ...]])

Inspect the state of the Pub/Sub subsystem. (see https://redis.io/commands/pubsub) โ€” peek behind the curtain, bestie ๐Ÿ‘€


๐Ÿ’ซ TRANSACTIONS ๐Ÿ’ซ

transactions are giving "all or nothing" and we respect the commitment. periodt. ๐Ÿ’…

discard

$r->discard()

Discard all commands issued after MULTI. (see https://redis.io/commands/discard) โ€” nvm, forget I said anything ๐Ÿ™ˆ

exec

$r->exec()

Execute all commands issued after MULTI. (see https://redis.io/commands/exec) โ€” do it, no takebacks ๐Ÿ”ฅ

multi

$r->multi()

Mark the start of a transaction block. (see https://redis.io/commands/multi) โ€” starting a group project, but actually good ๐Ÿ’–

unwatch

$r->unwatch()

Forget about all watched keys. (see https://redis.io/commands/unwatch) โ€” not watching anymore, it's giving boundaries โœจ

watch

$r->watch(key [key ...])

Watch the given keys to determine execution of the MULTI/EXEC block. (see https://redis.io/commands/watch) โ€” keeping an eye on things, lowkey stalker energy ๐Ÿ‘€


๐Ÿงš SCRIPTING ๐Ÿงš

lua scripts server-side? we love a little magic trick. abracadabra bestie. ๐Ÿช„

eval

$r->eval(script, numkeys, key [key ...], arg [arg ...])

Execute a Lua script server side. (see https://redis.io/commands/eval) โ€” run it, it's iconic ๐Ÿ’…

evalsha

$r->evalsha(sha1, numkeys, key [key ...], arg [arg ...])

Execute a Lua script server side. (see https://redis.io/commands/evalsha) โ€” same vibe, but with a sha1 glow-up โœจ

script_exists

$r->script_exists(script [script ...])

Check existence of scripts in the script cache. (see https://redis.io/commands/script-exists) โ€” do you exist? asking for a friend ๐Ÿซถ

script_flush

$r->script_flush()

Remove all the scripts from the script cache. (see https://redis.io/commands/script-flush) โ€” clean slate, we love a reset ๐Ÿงผ

script_kill

$r->script_kill()

Kill the script currently in execution. (see https://redis.io/commands/script-kill) โ€” dramatic exit, no cap ๐Ÿ’€

script_load

$r->script_load(script)

Load the specified Lua script into the script cache. (see https://redis.io/commands/script-load) โ€” upload that script, bestie ๐Ÿ’–


๐ŸŽ€ CONNECTION ๐ŸŽ€

connection commands are the "hey bestie" of Redis. let's get connected. ๐Ÿ”Œ

auth

$r->auth(password)

Authenticate to the server. (see https://redis.io/commands/auth) โ€” password check, slay ๐Ÿ”

$r->auth(username, password)

Authenticate to the server using Redis 6.0+ ACL System. (see https://redis.io/commands/auth) โ€” username and password? we love an upgrade ๐Ÿ’…

echo

$r->echo(message)

Echo the given string. (see https://redis.io/commands/echo) โ€” it's giving mirror mirror on the wall ๐Ÿชž

ping

$r->ping()

Ping the server. (see https://redis.io/commands/ping) โ€” are you there? it's me, bestie ๐Ÿ“ž

quit

$r->quit()

Close the connection. (see https://redis.io/commands/quit) โ€” goodbye, it was fun, see you never ๐Ÿ‘‹

select

$r->select(index)

Change the selected database for the current connection. (see https://redis.io/commands/select) โ€” switching lanes, main character move ๐Ÿš—

๐Ÿ–ฅ๏ธ SERVER ๐Ÿ–ฅ๏ธ

okay bestie, this is the server-side menu โ€” all the admin, config, list, and server-vibe commands. every single one is here, no skips, no cap. ๐Ÿ’…


๐Ÿซถ ACKNOWLEDGEMENTS ๐Ÿซถ

big love to the following people who contributed to this project (random order):

  • Aaron Crane (pipelining and AUTOLOAD caching support)
  • Dirk Vleugels
  • Flavio Poletti
  • Jeremy Zawodny
  • sunnavy at bestpractical.com
  • Thiago Berlitz Rondon
  • Ulrich Habel
  • Ivan Kruglov
  • Steffen Mueller <smueller@cpan.org>

๐Ÿ‘‘ AUTHORS ๐Ÿ‘‘

the masterminds behind this page:

  • Pedro Melo <melo@cpan.org>
  • Damien Krotkine <dams@cpan.org>

This software is Copyright (c) 2015 by Pedro Melo, Damien Krotkine.

This is free software, licensed under:

The Artistic License 2.0 (GPL Compatible)

periodt. ๐Ÿ’…


this page is Redis(3pm) from perl v5.36.0, dated 2023-01-14 โ€” hope this helped bestie, go slay ๐Ÿ’–โœจ

๐Ÿ“ฆ where this page comes from