Cache:...::Fast(3pm)

๐Ÿ“ฆ
version 0.28 ยท 5 versions
, in debian trixie, ubuntu resolute

๐Ÿ’– Cache::Memcached::Fast ๐Ÿ’–

okay bestie, gather round, because this is Cache::Memcached::Fast(3pm), straight out of the User Contributed Perl Documentation section, and it's literally a Perl client for memcached written in C. it's giving speed, it's giving low CPU, it's giving main character energy. โœจ


๐ŸŒธ NAME ๐ŸŒธ

Cache::Memcached::Fast โ€” a Perl client for memcached, written in C, no cap. ๐Ÿ’…


โœจ SYNOPSIS โœจ

use Cache::Memcached::Fast;

my $memd = Cache::Memcached::Fast->new({
    servers => [ { address => 'localhost:11211', weight => 2.5 },
                 '192.168.254.2:11211',
                 { address => '/path/to/unix.sock', noreply => 1 } ],
    namespace => 'my:',
    connect_timeout => 0.2,
    io_timeout => 0.5,
    close_on_error => 1,
    compress_threshold => 100_000,
    compress_ratio => 0.9,
    compress_methods => [ \&IO::Compress::Gzip::gzip,
                          \&IO::Uncompress::Gunzip::gunzip ],
    max_failures => 3,
    failure_timeout => 2,
    ketama_points => 150,
    nowait => 1,
    hash_namespace => 1,
    serialize_methods => [ \&Storable::freeze, \&Storable::thaw ],
    utf8 => 1,
    max_size => 512 * 1024,
});

# Get server versions.
my $versions = $memd->server_versions;
while (my ($server, $version) = each %$versions) {
    #...
}

# Store scalars.
$memd->add('skey', 'text');
$memd->add_multi(['skey2', 'text2'], ['skey3', 'text3', 10]);

$memd->replace('skey', 'val');
$memd->replace_multi(['skey2', 'val2'], ['skey3', 'val3']);

$memd->set('nkey', 5);
$memd->set_multi(['nkey2', 10], ['skey3', 'text', 5]);

# Store arbitrary Perl data structures.
my %hash = (a => 1, b => 2);
my @list = (1, 2);
$memd->set('hash', \%hash);
$memd->set_multi(['scalar', 1], ['list', \@list]);

# Add to strings.
$memd->prepend('skey', 'This is a ');
$memd->prepend_multi(['skey2', 'This is a '], ['skey3', 'prefix ']);
$memd->append('skey', 'ue.');
$memd->append_multi(['skey2', 'ue.'], ['skey3', ' suffix']);

# Do arithmetic.
$memd->incr('nkey', 10);
print "OK\n" if $memd->decr('nkey', 3) == 12;

my @counters = qw(c1 c2);
$memd->set_multi(map { [$_, 0] } @counters, 'c3', 'c4');
$memd->incr_multi(['c3', 2], @counters, ['c4', 10]);

# Retrieve values.
my $val = $memd->get('skey');
print "OK\n" if $val eq 'This is a value.';
my $href = $memd->get_multi('hash', 'nkey');
print "OK\n" if $href->{hash}->{b} == 2 and $href->{nkey} == 12;

# Do atomic test-and-set operations.
my $cas_val = $memd->gets('nkey');
$$cas_val[1] = 0 if $$cas_val[1] == 12;
if ($memd->cas('nkey', @$cas_val)) {
    print "OK, value updated\n";
} else {
    print "Update failed, probably another client"
        . " has updated the value\n";
}

# Delete some data.
$memd->delete('skey');

my @keys = qw(k1 k2 k3);
$memd->delete_multi(@keys);

# Wait for all commands that were executed in nowait mode.
$memd->nowait_push;

# Wipe out all cached data.
$memd->flush_all;

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Cache::Memcached::Fast is a Perl client for memcached, which is a memory cache daemon (peep http://www.memcached.org ๐Ÿ‘€). the module core is implemented in C, and it tries so hard to minimize the number of system calls and to avoid copying any keys or values, all for speed. the result? very low CPU consumption. it's giving efficiency, it's giving slay. ๐Ÿ”ฅ

the API is largely compatible with Cache::Memcached, the original pure Perl client, so most users of the original module can just install this one and add ::Fast to the old name in their scripts and keep it moving (full deets in "Compatibility with Cache::Memcached" below, bestie, we got you). ๐Ÿ’–


๐ŸŽ€ CONSTRUCTOR ๐ŸŽ€

๐Ÿ’… new

my $memd = Cache::Memcached::Fast->new($params);

creates a brand new client object, periodt. $params is a reference to a hash holding the client parameters. the keys it currently recognizes are:

โญ servers

servers => [ { address => 'localhost:11211', weight => 2.5 },
             '192.168.254.2:11211',
             { address => '/path/to/unix.sock', noreply => 1 } ],
(default: none)

the value is a reference to an array of server addresses. each address is either a scalar, a hash reference, or an array reference (that last one is for compatibility with Cache::Memcached, and it's deprecated, bestie, don't do it). if it's a hash reference, the keys are address (a scalar), weight (a positive rational number), and noreply (a boolean flag). the server address takes the form host:port for network TCP connections, or /path/to/unix.sock for local Unix socket connections. when weight isn't given, 1 is assumed. the client will distribute keys across servers proportionally to the server weights. โš–๏ธ

if you want key distribution that's compatible with Cache::Memcached, then all server weights should be integers, and their sum should be less than 32768. ๐Ÿงฎ

when noreply is enabled, commands executed in a void context will tell the server to not send the reply back. compare this with "nowait" below. the memcached server has implemented noreply starting with version 1.2.5. if you enable noreply for earlier server versions, things will go wrongly, and the client will eventually block. use with care. โš ๏ธ

โญ namespace

namespace => 'my::'
(default: '')

the value is a scalar that gets prepended to all key names passed to the memcached server. by using different namespaces, clients avoid interfering with each other. very demure, very mindful. ๐ŸŒธ

โญ hash_namespace

hash_namespace => 1
(default: disabled)

the value is a boolean that enables (true) or disables (false) the hashing of the namespace key prefix. by default, for compatibility with Cache::Memcached, the namespace prefix is not hashed along with the key. so like:

namespace => 'prefix/',
...
$memd->set('key', $val);

might use a different memcached server than:

namespace => '',
...
$memd->set('prefix/key', $val);

because the hash values of 'key' and 'prefix/key' may be different. ๐Ÿ™ˆ

but sometimes you need to hash the namespace prefix, like for interoperability with other clients that don't have the whole namespace concept. when hash_namespace is enabled, both examples above will use the same server โ€” the one that 'prefix/key' is mapped to. and note that there's no performance penalty then, because the namespace prefix is hashed only once. see "namespace". ๐Ÿ’–

โญ nowait

nowait => 1
(default: disabled)

the value is a boolean that enables (true) or disables (false) nowait mode. if it's enabled, when you call a method that only returns its success status (like set) in a void context, it sends the request to the server and returns immediately, not waiting for the reply. this avoids the round-trip latency, at the cost of an uncertain command outcome. ๐Ÿ˜ฌ

internally there's a counter of how many outstanding replies there should be, and on any command the client reads and discards any replies that have already arrived. when you later execute some method in a non-void context, all the outstanding replies will be waited for, and then the reply for this command will be read and returned. ๐Ÿ’…

โญ connect_timeout

connect_timeout => 0.7
(default: 0.25 seconds)

the value is a non-negative rational number of seconds to wait for a connection to establish. it applies only to network connections. zero disables the timeout, but keep in mind that operating systems have their own heuristic connect timeout. โฐ

note that the network connect process consists of several steps: destination host address lookup, which may return several addresses in the general case (especially for IPv6, see http://people.redhat.com/drepper/linux-rfc3484.html and http://people.redhat.com/drepper/userapi-ipv6.html), and then the attempt to connect to one of those addresses. connect_timeout applies only to one such connect, i.e. to one connect(2) call. so the overall connect process may take longer than connect_timeout seconds, but honestly that's unavoidable. ๐Ÿคทโ€โ™€๏ธ

โญ io_timeout (or the deprecated select_timeout)

io_timeout => 0.5
(default: 1.0 seconds)

the value is a non-negative rational number of seconds to wait before giving up on communicating with the server(s). zero disables the timeout. โณ

note that for commands that talk to more than one server (like get_multi), the timeout applies per server set, not per each server. so it won't expire if one server is quick enough to communicate, even if the others are being silent little ghosts. but if some servers are dead, the ones that are alive will finish communicating, and then the dead servers would timeout. ๐Ÿ’€

โญ close_on_error

close_on_error => 0
(default: enabled)

the value is a boolean that enables (true) or disables (false) close_on_error mode. when enabled, any error response from the memcached server makes the client close the connection. note that such an "error response" is different from a "negative response". the latter means the server processed the command and yielded a negative result. the former means the server failed to process the command for some reason. close_on_error is enabled by default, for safety. consider the following scenario, bestie, it's a whole saga:

  1. Client wants to set some value, but mistakenly sends a malformed command (this can't happen with the current module, of course ;)):
set key 10\r\n
value_data\r\n
  1. Memcached server reads the first line, 'set key 10', and can't parse it, because there's the wrong number of tokens in it. so it sends:
ERROR\r\n
  1. Then the server reads 'value_data' while it's in accept-command state! it can't parse it either (hopefully), and sends another:
ERROR\r\n

but the client expects one reply per command, so after sending the next command it will think that the second 'ERROR' is a reply for this new command. which means all replies will shift, including the replies for get commands! by closing the connection we eliminate such a possibility. ๐Ÿ›‘

when a connection dies, or the client receives a reply that it can't understand, it closes the socket regardless of the close_on_error setting. periodt. ๐Ÿ’…

โœจ compress_threshold

compress_threshold => 10_000
(default: -1)

so this one's an integer, bestie. when it's positive it means the threshold size in bytes โ€” anything whose size is equal to or bigger than this should get compressed. peep "compress_ratio" and "compress_methods" below for the rest of the tea.

a negative value just straight-up disables compression. bye. ๐Ÿ’…


๐ŸŽ€ compress_ratio

compress_ratio => 0.9
(default: 0.8)

a fractional number, and it lives strictly between 0 and 1. when "compress_threshold" kicks off the compression, the compressed size has to be less than or equal to (original-size * compress_ratio). if it ain't? the data gets stored uncompressed, no drama. ๐Ÿฆ‹


๐ŸŒธ compress_methods

compress_methods => [ \&IO::Compress::Gzip::gzip,
                      \&IO::Uncompress::Gunzip::gunzip ]
(default: [ sub { ${$_[1]} = Compress::Zlib::memGzip(${$_[0]}) },
            sub { ${$_[1]} = Compress::Zlib::memGunzip(${$_[0]}) } ]
 when Compress::Zlib is available)

a reference to an array holding two code refs โ€” compression routine and decompression routine, in that order, respectively. ๐Ÿ‘‘

the compression routine gets called when the size of the $value you passed to the "set" method family is greater than or equal to "compress_threshold" (and yeah, go look at "compress_ratio" too). the fact that compression happened gets remembered right alongside the data, so the decompression routine gets called on retrieval with the "get" method family.

the interface of these routines should be the exact same as the IO::Compress family (like, for instance, check IO::Compress::Gzip::gzip and IO::Uncompress::Gunzip::gunzip). so: compression routine takes a reference to a scalar value and a reference to a scalar where the compressed result will be stored. decompression routine takes a reference to a scalar with compressed data and a reference to a scalar where the uncompressed result will be stored. both routines should return true on success and false on error.

by default we roll with Compress::Zlib because, as of this writing, it's apparently much faster than IO::Uncompress::Gunzip. slay.


๐Ÿ’œ max_failures

max_failures => 3
(default: 0)

a non-negative integer, bestie. when it's positive: if there happened max_failures failures within failure_timeout seconds, the client does not try to connect to that particular server for another failure_timeout seconds. a value of zero disables this whole behaviour. ๐Ÿ˜Œ


๐Ÿฆ‹ failure_timeout

failure_timeout => 30
(default: 10 seconds)

a positive integer, number of seconds. go read "max_failures" for why you'd care. โœจ


๐Ÿ“ ketama_points

ketama_points => 150
(default: 0)

non-negative integer. when it's positive it enables the Ketama consistent hashing algorithm (<http://www.last.fm/user/RJ/journal/2007/04/10/392555/>), and it sets how many points the server with weight 1 gets mapped to. so each server gets mapped to ketama_points * weight points in the continuum. bigger value = more uniform distribution. ๐Ÿ’ซ

heads up though: the number of internal bucket structures โ€” and therefore memory consumption โ€” is proportional to the sum of those products. but the bucket structures themselves are tiny (two integers each), so you probably shouldn't stress about it, fr fr.

a value of zero disables the Ketama algorithm. also peep server weight in "servers" above.


๐Ÿงš serialize_methods

serialize_methods => [ \&Storable::freeze, \&Storable::thaw ],
(default: [ \&Storable::nfreeze, \&Storable::thaw ])

a reference to an array holding two code refs โ€” serialization routine and deserialization routine, respectively. ๐Ÿ’…

the serialization routine gets called when the $value passed to the "set" method family is a reference. the fact that serialization happened gets remembered along with the data, and the deserialization routine gets called on data retrieval with the "get" method family.

the interface should be the same as Storable::nfreeze and Storable::thaw. meaning: serialization routine takes a reference and returns a scalar string โ€” and it should not fail. deserialization routine takes a scalar string and returns a reference; if deserialization fails (like, wrong data format, oops ๐Ÿ™ˆ) it should throw an exception (call die). the module catches that exception, and "get" will then just pretend the key was never found. iconic behaviour honestly.


๐ŸŒˆ utf8

utf8 => 1
(default: disabled)

a boolean, bestie. true enables and false disables the conversion of Perl character strings into octet sequences in UTF-8 encoding on store, plus the reverse conversion on fetch (that's when the retrieved data is marked as being a UTF-8 octet sequence). see perlunicode. ๐Ÿฆ‹


โญ max_size

max_size => 512 * 1024
(default: 1024 * 1024)

the maximum size of an item to be stored in memcached. when you try to set a key to a value longer than max_size bytes (and yes, that's after serialization and compression), nothing gets sent to the server and the set methods return undef. ๐Ÿ’€

ngl, the real maximum on the server is actually less than 1MB, and it depends on key length among other things. so some values in the range [1MB - N bytes, 1MB], where N is several hundreds, will still get sent to the server and rejected there. you can set max_size to a smaller value to dodge that.

๐ŸŽ€ check_args

check_args => 'skip'
(default: not 'skip')

a string. currently the only recognized string is 'skip'.

by default, every constructor parameter name gets checked to make sure it's recognized, and you get a warning for any unknown parameter. this catches spelling errors that would otherwise go totally unnoticed, iykyk.

when you set it to 'skip', the check gets bypassed. you might want that when you share the same argument hash among different client versions, or among different clients. ๐Ÿ’…


๐Ÿ’– METHODS ๐Ÿ’–

๐Ÿ‘‘ enable_compress

$memd->enable_compress($enable);

turn compression on when the boolean $enable is true, and off when it's false.

careful bestie โ€” you can only enable compression when you set "compress_threshold" to some positive value and "compress_methods" is set.

Return: none.


๐Ÿฆ‹ namespace

$memd->namespace;
$memd->namespace($string);

with no argument, it returns the current namespace prefix. with an argument, it sets the namespace prefix to $string and returns the old prefix.

Return: a scalar โ€” the namespace prefix that was in effect before the call.


๐ŸŒธ set

$memd->set($key, $value);
$memd->set($key, $value, $expiration_time);

store the $value on the server under the $key. $key should be a scalar. $value should be defined and can be any Perl data type. when it's a reference, the referenced Perl data structure gets transparently serialized by the routines you specified with "serialize_methods" โ€” go read that one.

the optional $expiration_time is a positive integer, a number of seconds after which the value expires and isn't accessible anymore. โณ

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.


๐Ÿ“ set_multi

$memd->set_multi(
    [$key, $value],
    [$key, $value, $expiration_time],
    ...
);

like "set", but it operates on more than one key. takes a list of references to arrays, each one holding $key, $value and an optional $expiration_time.

heads up: multi commands are not all-or-nothing. some operations may succeed while others may fail. it's giving chaos, honestly.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. in scalar context, a hash reference is returned, where $href->{$key} holds the result value. go see "set" to learn what the result value actually is. ๐Ÿ’…


๐Ÿงš cas

$memd->cas($key, $cas, $value);
$memd->cas($key, $cas, $value, $expiration_time);

store the $value on the server under the $key, but only if the CAS (Consistent Access Storage) value associated with this key is equal to $cas. $cas is an opaque object returned with "gets" or "gets_multi" or "gats" or "gats_multi".

see "set" for the $key, $value, $expiration_time parameters description.

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error. so if the key exists on the server, a false would mean some other client has updated the value, and the "gets", "gats", "cas" command sequence should be repeated. ๐Ÿ”

the cas command first appeared in memcached 1.2.4.


๐Ÿ’œ cas_multi

$memd->cas_multi(
    [$key, $cas, $value],
    [$key, $cas, $value, $expiration_time],
    ...
);

like "cas", but it operates on more than one key. takes a list of references to arrays, each holding $key, $cas, $value and an optional $expiration_time.

again: multi commands are not all-or-nothing. some may succeed, some may fail. no cap.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. in scalar context, a hash reference is returned, where $href->{$key} holds the result value. see "cas" to learn what the result value is. โœจ

the cas command first appeared in memcached 1.2.4.


๐ŸŽ€ add

$memd->add($key, $value);
$memd->add($key, $value, $expiration_time);

store the $value on the server under the $key, but only if the key doesn't exist on the server. very exclusive, very main character energy. ๐Ÿ‘‘

see "set" for the $key, $value, $expiration_time parameters description.

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.


๐ŸŒˆ add_multi

$memd->add_multi(
    [$key, $value],
    [$key, $value, $expiration_time],
    ...
);

Like add, but it's doing the absolute most โ€” it works on more than one key at once. You pass it a list of arrayrefs, and each one holds $key, $value and an optional $expiration_time.

heads up bestie: multi commands are not all-or-nothing. Some operations may succeed, while others may fail. No take-backs, no group refund. ๐Ÿ’€

Return: in list context you get back the list of results, and each $list[$index] is the result value corresponding to the argument at position $index. In scalar context you get a hash reference, where $href->{$key} holds the result value. Peep "add" to learn what the result value is.


replace

$memd->replace($key, $value);
$memd->replace($key, $value, $expiration_time);

Store the $value on the server under the $key, but ONLY if the key already exists on the server. It's giving "you can't sit with us unless you're already seated." ๐Ÿ’…

See "set" for the $key, $value, $expiration_time parameters description.

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.


replace_multi

$memd->replace_multi(
    [$key, $value],
    [$key, $value, $expiration_time],
    ...
);

Like replace, but operates on more than one key. Takes the list of references to arrays, each holding $key, $value and an optional $expiration_time.

again for the people in the back: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "replace" to learn what the result value is.


append

$memd->append($key, $value);

Append the $value to the current value on the server under the $key. ๐Ÿซถ

$key and $value should be scalars, as well as the current value on the server. append doesn't affect the expiration time of the value โ€” it's just tacking stuff on the end, not resetting the timer, no cap.

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.

lore drop: the append command first appeared in memcached 1.2.4.

append_multi

$memd->append_multi(
    [$key, $value],
    ...
);

Like append, but operates on more than one key. Takes the list of references to arrays, each holding $key, $value.

say it with me: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "append" to learn what the result value is.

lore drop: the append command first appeared in memcached 1.2.4.

prepend

$memd->prepend($key, $value);

Prepend the $value to the current value on the server under the $key โ€” front of the line energy, main character placement. ๐Ÿ‘‘

$key and $value should be scalars, as well as the current value on the server. prepend doesn't affect the expiration time of the value.

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.

lore drop: the prepend command first appeared in memcached 1.2.4.

prepend_multi

$memd->prepend_multi(
    [$key, $value],
    ...
);

Like prepend, but operates on more than one key. Takes the list of references to arrays, each holding $key, $value.

one more time: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "prepend" to learn what the result value is.

lore drop: the prepend command first appeared in memcached 1.2.4.

get

$memd->get($key);

Retrieve the value for a $key. $key should be a scalar. โœจ

Return: the value associated with the $key, or nothing.


get_multi

$memd->get_multi(@keys);

Retrieve several values associated with @keys. @keys should be an array of scalars. Bulk-fetching, we love efficiency. ๐ŸŒธ

Return: a reference to a hash, where $href->{$key} holds the corresponding value.


gets

$memd->gets($key);

Retrieve the value and its CAS for a $key. $key should be a scalar.

Return: a reference to an array [$cas, $value], or nothing. And the slay part? You may conveniently pass it right back to cas with @$res:

my $cas_val = $memd->gets($key);
# Update value.
if (defined $cas_val) {
    $$cas_val[1] = 3;
    $memd->cas($key, @$cas_val);
}
lore drop: the gets command first appeared in memcached 1.2.4.

gets_multi

$memd->gets_multi(@keys);

Retrieve several values and their CASs associated with @keys. @keys should be an array of scalars.

Return: a reference to a hash, where $href->{$key} holds a reference to an array [$cas, $value]. Compare with "gets".

lore drop: the gets command first appeared in memcached 1.2.4.

incr

$memd->incr($key);
$memd->incr($key, $increment);

Increment the value for the $key. Starting with memcached 1.3.3, $key should be set to a number or the command will fail โ€” no vibes-based math allowed. An optional $increment should be a positive integer, and when it's not given, 1 is assumed. Note that the server doesn't check for overflow. ๐Ÿซ 

Return: an unsigned integer, the new value for the $key, or false for a negative server reply, or undef in case of some error.


incr_multi

$memd->incr_multi(
    @keys,
    [$key],
    [$key, $increment],
    ...
);

Like incr, but operates on more than one key. Takes the list of keys and references to arrays, each holding $key and an optional $increment.

you know the drill: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "incr" to learn what the result value is.


decr

$memd->decr($key);
$memd->decr($key, $decrement);

Decrement the value for the $key. Starting with memcached 1.3.3, $key should be set to a number or the command will fail. An optional $decrement should be a positive integer, and when it's not given, 1 is assumed. And here's the plot twist: the server does check for underflow โ€” an attempt to decrement the value below zero would set the value to zero. Similar to DBI, zero is returned as "0E0", and evaluates to true in a boolean context. ๐Ÿ˜ญ

Return: an unsigned integer, the new value for the $key, or false for a negative server reply, or undef in case of some error.


decr_multi

$memd->decr_multi(
    @keys,
    [$key],
    [$key, $decrement],
    ...
);

Like decr, but operates on more than one key. Takes the list of keys and references to arrays, each holding $key and an optional $decrement.

fr fr: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "decr" to learn what the result value is.


delete

$memd->delete($key);

Delete $key and its value from the cache. Gone. Poof. Blocked. ๐Ÿฆ‹

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.


remove (deprecated)

Alias for "delete", for compatibility with Cache::Memcached.

it's deprecated, bestie. Still there for the old heads, but you know what to use instead.

delete_multi

$memd->delete_multi(@keys);

Like delete, but operates on more than one key. Takes the list of keys.

yes, again: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "delete" to learn what the result value is.


touch

$memd->touch($key, $expiration_time);

Update the expiration time of $key without fetching it. It's giving glow-up without the screenshot. โœจ

The optional $expiration_time is a positive integer number of seconds after which the value will expire and wouldn't be accessible any longer.

Return: boolean โ€” true for a positive server reply, false for a negative server reply, or undef in case of some error.

lore drop: the touch command first appeared in memcached 1.4.8.

touch_multi

$memd->touch_multi(
    [$key],
    [$key, $expiration_time],
    ...
);

Like touch, but operates on more than one key. Takes the list of references to arrays, each holding $key and an optional $expiration_time.

multis stay chaotic: multi commands are not all-or-nothing. Some operations may succeed, while others may fail.

Return: in list context, the list of results, where each $list[$index] is the result value corresponding to the argument at position $index. In scalar context, a hash reference, where $href->{$key} holds the result value. See "touch" to learn what the result value is.

lore drop: the touch command first appeared in memcached 1.4.8.

gat

$memd->gat($expiration_time, $key);

Update the expiration time and retrieve the value for a $key โ€” two birds, one iconic little command. ๐ŸŽ€

$key should be a scalar. $expiration_time is a positive integer number of seconds after which the value will expire and wouldn't be accessible any longer.

Return: the value associated with the $key, or nothing.

lore drop: the gat command first appeared in memcached 1.5.3.

gat_multi

$memd->gat_multi($expiration_time, @keys);

Update the expiration time of the @keys and get the associated values. @keys should be an array of scalars.

Return: a reference to a hash, where $href->{$key} holds the corresponding value.

lore drop: the gat command first appeared in memcached 1.5.3.

gats

$memd->gats($expiration_time, $key);

Update the expiration time and Retrieve the value and its CAS for a $key. ๐Ÿ’–

Return: reference to an array [$cas, $value], or nothing. You may conveniently pass it back to cas with @$res:

my $cas_val = $memd->gats($expiration_time, $key);
# Update value.
if (defined $cas_val) {
    $$cas_val[1] = 3;
    $memd->cas($key, @$cas_val);
}

gat command first appeared in memcached 1.5.3. ๐Ÿฃ

gats_multi

$memd->gats_multi($expiration_time, @keys);

Update the expiration time and retrieve several values and their CASs associated with @keys. @keys should be an array of scalars.

Return: reference to hash, where $href->{$key} holds a reference to an array [$cas, $value]. Compare with gats.

gat command first appeared in memcached 1.5.3. ๐Ÿฃ

flush_all

$memd->flush_all;
$memd->flush_all($delay);

Flush all caches the client knows about. This command invalidates all items in the caches, none of them will be returned on subsequent retrieval command. $delay is an optional non-negative integer number of seconds to delay the operation. The delay will be distributed across the servers. For instance, when you have three servers, and call flush_all(30), the servers would get 30, 15, 0 seconds delays respectively. When omitted, zero is assumed, i.e. flush immediately.

Return: reference to hash, where $href->{$server} holds corresponding result value. $server is either host:port or /path/to/unix.sock, as described in servers. Result value is a boolean, true for positive server reply, false for negative server reply, or undef in case of some error.

nowait_push

$memd->nowait_push;

Push all pending requests to the server(s), and wait for all replies. When nowait mode is enabled, the requests issued in a void context may not reach the server(s) immediately (because the reply is not waited for). Instead they may stay in the send queue on the local host, or in the receive queue on the remote host(s), for quite a long time. This method ensures that they are delivered to the server(s), processed there, and the replies have arrived (or some error has happened that caused some connection(s) to be closed).

Destructor will call this method to ensure that all requests are processed before the connection is closed.

Return: nothing.

server_versions

$memd->server_versions;

Get server versions.

Return: reference to hash, where $href->{$server} holds corresponding server version. $server is either host:port or /path/to/unix.sock, as described in servers.

disconnect_all

$memd->disconnect_all;

Closes all open sockets to memcached servers. Must be called after fork in perlfunc if the parent process has open sockets to memcacheds (as the child process inherits the socket and thus two processes end up using the same socket which leads to protocol errors.)

Return: nothing.

Compatibility with Cache::Memcached

This module is designed to be a drop in replacement for Cache::Memcached. Where constructor parameters are the same as in Cache::Memcached, the default values are also the same, and new parameters are disabled by default (the exception is close_on_error, which is absent in Cache::Memcached and enabled by default in this module, and check_args, which see). Internally Cache::Memcached::Fast uses the same hash function as Cache::Memcached, and thus should distribute the keys across several servers the same way. So both modules may be used interchangeably. Most users of the original module should be able to use this module after replacing Cache::Memcached with Cache::Memcached::Fast, without further code modifications. However, as of this release, the following features of Cache::Memcached are not supported by Cache::Memcached::Fast (and some of them will never be):

Constructor parameters

no_rehash

Current implementation never rehashes keys, instead max_failures and failure_timeout are used.

If the client would rehash the keys, a consistency problem would arise: when the failure occurs the client can't tell whether the server is down, or there's a (transient) network failure. While some clients might fail to reach a particular server, others may still reach it, so some clients will start rehashing, while others will not, and they will no longer agree which key goes where.

readonly

Not supported. Easy to add. However I'm not sure about the demand for it, and it will slow down things a bit (because from design point of view it's better to add it on Perl side rather than on XS side).

debug

Not supported. Since the implementation is different, there can't be any compatibility on debug level.

Methods

Passing keys

Every key should be a scalar. The syntax when key is a reference to an array [$precomputed_hash, $key] is not supported.

set_servers

Not supported. Server set should not change after client object construction.

set_debug

Not supported. See debug.

set_readonly

Not supported. See readonly.

set_norehash

Not supported. See no_rehash.

set_compress_threshold

Not supported. Easy to add. Currently you specify compress_threshold during client object construction.

stats

Not supported. Perhaps will appear in the future releases.

Tainted data

In current implementation tainted flag is neither tested nor preserved, storing tainted data and retrieving it back would clear tainted flag. See perlsec.

Threads

This module is thread-safe when used with Perl >= 5.7.2. As with other Perl data each thread gets its own copy of Cache::Memcached::Fast object that is in scope when the thread is created. Such copies share no state, and may be used concurrently. For example:

use threads;

my $memd = Cache::Memcached::Fast->new({...});

sub thread_job {
  $memd->set("key", "thread value");
}

threads->new(\&thread_job);
$memd->set("key", "main value");

Here both sets will be executed concurrently, and the value of key will be either main value or thread value, depending on the timing of operations. Note that $memd inside thread_job internally refers to a different Cache::Memcached::Fast object than $memd from the outer scope. Each object has its own connections to servers, its own counter of outstanding replies for nowait mode, etc.

New object copy is created with the same constructor arguments, but initially is not connected to any server (even when master copy has open connections). No file descriptor is allocated until the command is executed through this new object.

You may safely create Cache::Memcached::Fast object from threads other than main thread, and/or pass them as parameters to threads::new(). However you can't return the object from top-level thread function. I.e., the following won't work:

use threads;

sub thread_job {
  return Cache::Memcached::Fast->new({...});
}

my $thread = threads->new(\&thread_job);

my $memd = $thread->join;  # The object will be destroyed here.

This is a Perl limitation (see BUGS AND LIMITATIONS in threads).

SUPPORT

The code repository is available for public review and contribution at <https://github.com/JRaspass/Cache-Memcached-Fast>.

Please report any bugs or feature requests through the issue tracker at <https://github.com/JRaspass/Cache-Memcached-Fast/issues>.

SEE ALSO

AUTHORS

  • Tomash Brechko <tomash.brechko@gmail.com> - design and implementation.
  • Michael Monashev <postmaster@softsearch.ru> - project management, design suggestions, testing.
  • James Raspass <jraspass@gmail.com> - recent additions and current maintenance.

ACKNOWLEDGEMENTS

Development of this module was sponsored by Monashev Co. Ltd.

Thanks to Peter J. Holzer for enlightening on UTF-8 support.

Thanks to Yasuhiro Matsumoto for the initial Win32 patch.

Copyright ยฉ 2007-2010 Tomash Brechko. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


This page was served fresh from perl v5.40.1 on 2025-05-10 and lives at Cache:...::Fast(3pm). Stay slaying, bestie! ๐Ÿ’…โœจ

๐Ÿ“ฆ where this page comes from