Redis(3pm)
๐ 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/sockunix:/path/to/sock127.0.0.1:11011tcp: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
subscribethese last two are the same, always. But withpsubscribe, 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. ๐
bgrewriteaofโ$r->bgrewriteaof()โ asynchronously rewrite the append-only file, like a lil glow-up for your AOF โจ (seehttps://redis.io/commands/bgrewriteaof)bgsaveโ$r->bgsave()โ asynchronously save the dataset to disk, background vibes only ๐พ (seehttps://redis.io/commands/bgsave)client_getnameโ$r->client_getname()โ get the current connection name, iykyk ๐ท๏ธ (seehttps://redis.io/commands/client-getname)client_killโ$r->client_kill([ip:port], [ID client-id], [TYPE normal|slave|pubsub], [ADDR ip:port], [SKIPME yes/no])โ kill the connection of a client, bye bestie ๐ (seehttps://redis.io/commands/client-kill)client_listโ$r->client_list()โ get the list of client connections (seehttps://redis.io/commands/client-list)client_pauseโ$r->client_pause(timeout)โ stop processing commands from clients for some time, like a timeout but for the whole server โธ๏ธ (seehttps://redis.io/commands/client-pause)client_setnameโ$r->client_setname(connection-name)โ set the current connection name (seehttps://redis.io/commands/client-setname)cluster_slotsโ$r->cluster_slots()โ get array of Cluster slot to node mappings (seehttps://redis.io/commands/cluster-slots)commandโ$r->command()โ get array of Redis command details (seehttps://redis.io/commands/command)command_countโ$r->command_count()โ get total number of Redis commands (seehttps://redis.io/commands/command-count)command_getkeysโ$r->command_getkeys()โ extract keys given a full Redis command (seehttps://redis.io/commands/command-getkeys)command_infoโ$r->command_info(command-name [command-name ...])โ get array of specific Redis command details (seehttps://redis.io/commands/command-info)config_getโ$r->config_get(parameter)โ get the value of a configuration parameter (seehttps://redis.io/commands/config-get)config_resetstatโ$r->config_resetstat()โ reset the stats returned by INFO (seehttps://redis.io/commands/config-resetstat)config_rewriteโ$r->config_rewrite()โ rewrite the configuration file with the in memory configuration (seehttps://redis.io/commands/config-rewrite)config_setโ$r->config_set(parameter, value)โ set a configuration parameter to the given value (seehttps://redis.io/commands/config-set)dbsizeโ$r->dbsize()โ return the number of keys in the selected database (seehttps://redis.io/commands/dbsize)debug_objectโ$r->debug_object(key)โ get debugging information about a key (seehttps://redis.io/commands/debug-object)debug_segfaultโ$r->debug_segfault()โ make the server crash ๐ yes literally, it's a debug command, be careful bestie (seehttps://redis.io/commands/debug-segfault)flushallโ$r->flushall()โ remove all keys from all databases, like a full reset but scary ๐ญ (seehttps://redis.io/commands/flushall)flushdbโ$r->flushdb()โ remove all keys from the current database (seehttps://redis.io/commands/flushdb)infoโ$r->info([section])โ get information and statistics about the server (seehttps://redis.io/commands/info)lastsaveโ$r->lastsave()โ get the UNIX time stamp of the last successful save to disk (seehttps://redis.io/commands/lastsave)lindexโ$r->lindex(key, index)โ get an element from a list by its index (seehttps://redis.io/commands/lindex)linsertโ$r->linsert(key, BEFORE|AFTER, pivot, value)โ insert an element before or after another element in a list (seehttps://redis.io/commands/linsert)llenโ$r->llen(key)โ get the length of a list (seehttps://redis.io/commands/llen)lpopโ$r->lpop(key)โ remove and get the first element in a list (seehttps://redis.io/commands/lpop)lpushโ$r->lpush(key, value [value ...])โ prepend one or multiple values to a list (seehttps://redis.io/commands/lpush)lpushxโ$r->lpushx(key, value)โ prepend a value to a list, only if the list exists (seehttps://redis.io/commands/lpushx)lrangeโ$r->lrange(key, start, stop)โ get a range of elements from a list (seehttps://redis.io/commands/lrange)lremโ$r->lrem(key, count, value)โ remove elements from a list (seehttps://redis.io/commands/lrem)lsetโ$r->lset(key, index, value)โ set the value of an element in a list by its index (seehttps://redis.io/commands/lset)ltrimโ$r->ltrim(key, start, stop)โ trim a list to the specified range (seehttps://redis.io/commands/ltrim)monitorโ$r->monitor()โ listen for all requests received by the server in real time (seehttps://redis.io/commands/monitor)roleโ$r->role()โ return the role of the instance in the context of replication (seehttps://redis.io/commands/role)rpopโ$r->rpop(key)โ remove and get the last element in a list (seehttps://redis.io/commands/rpop)rpoplpushโ$r->rpoplpush(source, destination)โ remove the last element in a list, append it to another list and return it (seehttps://redis.io/commands/rpoplpush)rpushโ$r->rpush(key, value [value ...])โ append one or multiple values to a list (seehttps://redis.io/commands/rpush)rpushxโ$r->rpushx(key, value)โ append a value to a list, only if the list exists (seehttps://redis.io/commands/rpushx)saveโ$r->save()โ synchronously save the dataset to disk (seehttps://redis.io/commands/save)shutdownโ$r->shutdown([NOSAVE], [SAVE])โ synchronously save the dataset to disk and then shut down the server (seehttps://redis.io/commands/shutdown)slaveofโ$r->slaveof(host, port)โ make the server a slave of another instance, or promote it as master (seehttps://redis.io/commands/slaveof)slowlogโ$r->slowlog(subcommand, [argument])โ manages the Redis slow queries log (seehttps://redis.io/commands/slowlog)syncโ$r->sync()โ internal command used for replication (seehttps://redis.io/commands/sync)timeโ$r->time()โ return the current server time (seehttps://redis.io/commands/time)
๐ซถ 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>
๐ COPYRIGHT AND LICENSE ๐
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
- debian bookworm: libredis-perl 2:2.000-1 ยท Artistic-2.0
- debian trixie: libredis-perl 2:2.000-1 ยท Artistic-2.0
- ubuntu noble: libredis-perl 2:2.000-1 ยท Artistic-2.0
- ubuntu resolute: libredis-perl 2:2.000-1 ยท Artistic-2.0
- ubuntu stonking: libredis-perl 2:2.000-1 ยท Artistic-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms