Cache:...cached(3pm)

πŸ“¦
version 0.04001 Β· 2 versions
  • 0.04001 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.04001 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

🌸 Cache::Memcached::libmemcached πŸ’–

okay bestie, sit down, hydrate, because this is the User Contributed Perl Documentation page for Cache:...cached(3pm) and it's a whole mood. it's part 1 of 2 btw, so don't go anywhere. 🫢


✨ NAME ✨

Cache::Memcached::libmemcached β€” Cache interface to Memcached::libmemcached

like, that's it. that's the name. iconic. πŸ‘‘


πŸŽ€ SYNOPSIS πŸŽ€

use Cache::Memcached::libmemcached;

my $memd = Cache::Memcached::libmemcached->new({
    servers => [
          "10.0.0.15:11211",
          [ "10.0.0.15:11212", 2 ], # weight
          "/var/sock/memcached"
    ],
    compress_threshold => 10_000,
    # ... many more options supported
});

$memd->set("my_key", "Some value");
$memd->set("object_key", { 'complex' => [ "object", 2, 4 ]});

$val = $memd->get("my_key");
$val = $memd->get("object_key");
print $val->{complex}->[2] if $val;

$memd->incr("key");
$memd->decr("key");
$memd->incr("key", 2);

$memd->delete("key");
$memd->remove("key"); # Alias to delete

my $hashref = $memd->get_multi(@keys);

# Import Memcached::libmemcached constants - explicitly by name or by tags
# see Memcached::libmemcached::constants for a list
use Cache::Memcached::libmemcached qw(MEMCACHED_DISTRIBUTION_CONSISTENT);
use Cache::Memcached::libmemcached qw(
    :defines
    :memcached_allocated
    :memcached_behavior
    :memcached_callback
    :memcached_connection
    :memcached_hash
    :memcached_return
    :memcached_server_distribution
);

my $memd = Cache::Memcached::libmemcached->new({
    distribution_method => MEMCACHED_DISTRIBUTION_CONSISTENT,
    hashing_algorithm   => MEMCACHED_HASH_FNV1A_32,
    behavior_... => ...,
    ...
});

ok so that's the whole vibe in one code block. servers, compression, hashing, constants β€” she does it all. πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

so. this is the Cache::Memcached-compatible interface to libmemcached, which is a C library for talking to memcached. no cap.

Cache::Memcached::libmemcached is built on top of Memcached::libmemcached. and here's the tea: while Memcached::libmemcached is out here trying to port the libmemcached API straight to perl, Cache::Memcached::libmemcached is trying to be API compatible with Cache::Memcached so you can literally use it as a drop-in replacement. slay.

also Cache::Memcached::libmemcached inherits from Memcached::libmemcached. and like, you are free to use the Memcached::libmemcached-specific methods directly on the object, nobody's stopping you β€” but doing that means your code is no longer compatible with the original Cache::Memcached API. which means you lose some of the portability in case you ever wanna swap it out for some other package. so, y'know. choose wisely bestie. πŸ™ˆ


πŸ’– Cache::Memcached COMPATIBLE METHODS πŸ’–

except for the minor incompatibilities (yes there are some, we'll get there), these methods are compatible with Cache::Memcached. periodt.

🌟 new

takes one parameter, a hashref of options. that's the whole thing.

Cache::Memcached options:

  • servers β€” the value gets passed to the set_servers method.
  • compress_threshold β€” sets a compression threshold, in bytes. values larger than this threshold get compressed by set and decompressed by get. ✨
  • namespace β€” the value gets passed to the namespace method.
  • debug β€” sets the trace_level for the Memcached::libmemcached object.
  • readonly, no_rehash β€” 🚨 these Cache::Memcached options are NOT supported. don't come for me, that's just the facts.

options specific to Cache::Memcached::libmemcached:

  • compress_savings
  • behavior_* β€” any of the many behaviors documented in Memcached::libmemcached::memcached_behavior can be specified by using argument key names that start with behavior_. for example:
behavior_ketama_weighted => 1,
behavior_noreply => 1,
behavior_number_of_replicas => 2,
behavior_server_failure_limit => 3,
behavior_auto_eject_hosts => 1,
  • no_block
  • hashing_algorithm
  • distribution_method
  • binary_protocol
and for these four β€” no_block, hashing_algorithm, distribution_method, binary_protocol β€” they're equivalent to the same options prefixed with behavior_. iykyk. πŸ’…

πŸŽ€ set_servers

$memd->set_servers( [ 'serv1:port1', 'serv2:port2', ... ]);

calls server_add for each element of the supplied arrayref. and if you wanna know what counts as a valid value β€” including how to specify weights β€” go peek at server_add. she explains everything. 🫢

🌸 namespace

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

no argument? it returns the current namespace prefix. with the argument? it sets the namespace prefix to $string and returns the old prefix. so it's giving getter and setter energy at the same time.

the effect is that it prefixes all keys with the namespace value you gave it. so like, if you set namespace to "app1:" and later do a set of "foo" to "bar", memcached is actually seeing you set "app1:foo" to "bar". sneaky. obsessed.

⚠️ the namespace string must be less than 128 bytes (MEMCACHED_PREFIX_KEY_MAX_SIZE). keep it cute and keep it short.

πŸ¦‹ get

my $val = $memd->get($key);

retrieves a key from the memcached. returns the value (automatically thawed with Storable, if necessary) or undef.

heads up: currently the arrayref form of $key is NOT supported. perhaps in the future. perhaps. 🀷

⭐ get_multi

my $hashref = $memd->get_multi(@keys);

retrieves multiple keys from the memcache while doing just one query. efficiency queen. returns a hashref of the key/value pairs that were actually available.

πŸ’œ set

$memd->set($key, $value[, $expires]);

unconditionally sets a key to a given value in the memcache. returns true if it was stored successfully. no questions asked, no conditions, just vibes.

same deal as get: the arrayref form of $key is NOT supported currently. perhaps in the future.

🌈 add

$memd->add($key, $value[, $expires]);

like set(), but it only stores in memcache if the key doesn't already exist. she's exclusive like that.

πŸŽ€ replace

$memd->replace($key, $value[, $expires]);

like set(), but it only stores in memcache if the key already exists. can't make something out of nothing, bestie.

✨ append

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

appends $value to whatever value is associated with $key. only available for memcached > 1.2.4 btw.

🌸 prepend

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

prepends $value to whatever value is associated with $key. also only available for memcached > 1.2.4.

πŸ‘‘ incr / decr

my $newval = $memd->incr($key);
my $newval = $memd->decr($key);

my $newval = $memd->incr($key, $offset);
my $newval = $memd->decr($key, $offset);

atomically increments or decrements the integer value specified by $key. returns undef if the key doesn't exist on the server. 😭

πŸ’€ delete / remove

$memd->delete($key);
$memd->delete($key, $time);

deletes a key. remove is an alias for it, same energy, different name.

if $time is non-zero then the item is marked for later expiration. expiration works by placing the item into a delete queue, which means it won't be possible to retrieve it by the get command, but the add and replace commands with this key will also fail (the set command will succeed, however). after the time passes, the item is finally deleted from server memory. she's on a timer. πŸ’…

🧚 flush_all

$memd->fush_all;

runs the memcached flush_all command on all configured hosts, emptying all their caches. every last one. gone. poof. πŸ”₯

πŸ“ set_compress_threshold

$memd->set_compress_threshold($threshold);

sets the compress threshold. that's the whole bit.

πŸ’– enable_compress

$memd->enable_compress($bool);

this is actually an alias to set_compress_enable(). the original version from Cache::Memcached is, despite its naming, a setter as well. naming is hard, we don't judge. πŸ™ˆ

🌟 stats

my $h = $memd->stats();
my $h = $memd->stats($keys);

returns a hashref of statistical data regarding the memcache server(s), the $memd object, or both. $keys can be an arrayref of keys wanted, a single key wanted, or absent β€” in which case the default value is [ '' ]. for each key, the stats command is run on each server.

for example $memd->stats([ '', 'sizes' ]) would return a structure like this:

{
    hosts => {
        'N.N.N.N:P' => {
            misc => {
                ...
            },
            sizes => {
                ...
            },
        },
        ...,
    },
    totals => {
        ...
    }
}

the general stats (where the key is "") are returned with a key of misc. and the totals element contains the aggregate totals for all hosts of some of the statistics. number crunching queen. πŸ‘‘

🌈 disconnect_all

disconnects from servers. bye bestie. πŸ‘‹

πŸ’œ cas

$memd->cas($key, $cas, $value[, $exptime]);

overwrites data in the server as long as the cas value is still the same in the server. like a vibe check before committing.

you can get the cas value of a result by calling memcached_result_cas() on a memcached_result_st(3) structure.

⚠️ support for cas is disabled by default because there's a slight performance penalty. to enable it, use the support_cas option to new. periodt.

πŸŽ€ Cache::Memcached::Fast COMPATIBLE METHODS πŸŽ€

⭐ server_versions

$href = $memd->server_versions;

returns a reference to a hash, where $href->{$server} holds the corresponding server version string, e.g. "1.4.4". and $server is either host:port or /path/to/unix.sock. so you can literally ask each server what version it's running. nosy in the best way. πŸ¦‹


πŸ’… Cache::Memcached::libmemcached SPECIFIC METHODS πŸ’…

these methods are libmemcached-specific. not like the others, and that's fine.

🌸 server_add

$self->server_add( $server_host_port );   # 10.10.10.10:11211
$self->server_add( $server_socket_path ); # /path/to/socket
$self->server_add( [ $server, $weight ] );
$self->server_add( { address => $server, weight => $weight } );

adds a memcached server address with an optional weight (default 0). pick whichever form speaks to you. ✨


🧚 UTILITY METHODS 🧚

🚨 WARNING: please do not consider the existence of these methods to be final. they may be renamed or may entirely disappear from future releases. so don't get too attached. 😭
  • get_compress_threshold β€” return the current value of compress_threshold.
  • set_compress_enable β€” set the value of compress_enable.
  • get_compress_enable β€” return the current value of compress_enable.
  • set_compress_savings β€” set the value of compress_savings.
  • get_compress_savings β€” return the current value of compress_savings.

πŸ”₯ BEHAVIOR CUSTOMIZATION πŸ”₯

Memcached::libmemcached supports many 'behaviors' that can be used to configure the behavior of the library and its interaction with the servers.

certain libmemcached behaviors can be configured with the following methods.

(NOTE: this API is not fixed yet. it's giving beta energy.)

πŸ’œ set_no_block

$memd->set_no_block( 1 );

set to use blocking / non-blocking I/O.

🚨 when this is in effect, get() becomes flaky, so don't attempt to call it. this has the most effect for set() operations, because libmemcached stops waiting for server response after writing to the socket (set() will also always return success).

please consult the man page for memcached_behavior_set() for details before setting. fr fr, read it first.

πŸ¦‹ is_no_block

get the current value of the no_block behavior.

⭐ set_distribution_method

$memd->set_distribution_method( MEMCACHED_DISTRIBUTION_CONSISTENT );

set the distribution behavior.

🌸 get_distribution_method

get the distribution behavior.

πŸŽ€ set_hashing_algorithm

$memd->set_hashing_algorithm( MEMCACHED_HASH_KETAMA );

set the hashing algorithm used.

πŸ’– get_hashing_algorithm

get the hashing algorithm used.

πŸ‘‘ set_binary_protocol / is_binary_protocol

$memd->set_binary_protocol( 1 );
$binary = $memd->is_binary_protocol();

use set_binary_protocol to enable/disable binary protocol. use is_binary_protocol to determine the current setting. cute little pair, they come together. 🫢

πŸ”₯ OPTIMIZE FLAG πŸ”₯

okay bestie, listen up πŸ‘‚ if you are 100% sure that you won't be using the master key support (that's the one where you provide an arrayref as the key) you can get about 4~5% performance boost by setting the environment variable named PERL_LIBMEMCACHED_OPTIMIZE to a true value before loading the module. periodt πŸ’…

This is an EXPERIMENTAL optimization and will possibly be replaced by implementing the methods in C in Memcached::libmemcached. so like, enjoy it while it lasts fr fr 😭

🌈 VARIOUS MEMCACHED MODULES 🌈

Below are the various memcached modules available on CPAN. it's giving options ✨

Please check tool/benchmark.pl for a live comparison of these modules. (except for Cache::Memcached::XS, which I wasn't able to compile under my main dev environment πŸ˜”)

πŸ’– Cache::Memcached πŸ’–

This is the "original" module. It's mostly written in Perl, is slow, and lacks significant features like support for the binary protocol. no cap, it's the grandma of the group πŸ‘΅

πŸ’– Cache::Memcached::libmemcached πŸ’–

Cache::Memcached::libmemcached, this module, is a perl binding for libmemcached (http://tangent.org/552/libmemcached.html). Not to be confused with libmemcache (see below). iykyk πŸ‘‘

πŸ’– Cache::Memcached::Fast πŸ’–

Cache::Memcached::Fast is a memcached client written in XS from scratch. As of this writing benchmarks shows that Cache::Memcached::Fast is faster on get_multi(), and Cache::Memcached::libmemcached is faster on regular get()/set(). Cache::Memcached::Fast doesn't support the binary protocol. the way they each have their own slay era πŸ¦‹

πŸ’– Memcached::libmemcached πŸ’–

Memcached::libmemcached is a thin binding to the libmemcached C library and provides access to most of the libmemcached API. it's giving thin but make it powerful ✨

If you don't care about a drop-in replacement for Cache::Memcached, and want to benefit from the feature-rich efficient API that libmemcached offers, this is the way to go. main character energy tbh πŸŽ€

Since the Memcached::libmemcached module is also the parent class of this module you can call Memcached::libmemcached methods directly. inherited queen πŸ‘‘

πŸ’– Cache::Memcached::XS πŸ’–

Cache::Memcached::XS is a binding for libmemcache (http://people.freebsd.org/~seanc/libmemcache/). The main memcached site at http://danga.com/memcached/apis.bml seems to indicate that the underlying libmemcache is no longer in active development. The module hasn't been updated since 2006. not the 2006 πŸ’€ like it's been in the group chat but never replied since 2006 😭


πŸ“ TODO πŸ“

  • Check and improve compatibility with Cache::Memcached::Fast. compatibility glow-up pending πŸ’…
  • Add forget_dead_hosts() for greater Cache::Memcached compatibility? asking for a friend πŸ‘€
  • Treat PERL_LIBMEMCACHED_OPTIMIZE as the default and add a subclass that handles the arrayref master key concept. Then the custom methods (get set add replace prepend append cas delete) can then all be removed and the libmemcached ones used directly. Alternatively, add master key via array ref support to the methods in ::libmemcached. Either way the effect on performance should be significant. big brain plans fr fr 🧠
  • Redo tools/benchmarks.pl performance tests (ensuring that methods are not called in void context unless it's appropriate). benchmark girlies rise 🌸
  • Try using Cache::Memcached::Fast's test suite to test this module. Via private lib/Cache/Memcached/libmemcachedAsFast.pm wrapper. stealing the test suite? iconic behavior actually 😌
  • Implement automatic no-reply on calls in void context (like Cache::Memcached::Fast). That should yield a signigicant performance boost. (typo and all, we move πŸ’€) speed speed speed πŸ”₯

πŸ‘‘ AUTHOR πŸ‘‘

Copyright (c) 2008 Daisuke Maki <daisuke@endeworks.jp>

With contributions by Tim Bunce. two legends, one file 🫢


πŸ“œ LICENSE πŸ“œ

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

See http://www.perl.com/perl/misc/Artistic.html


and that's the whole page, bestie ✨ this little manual was served fresh from perl v5.36.0 on 2022-12-04, and yeah the header says Cache:...cached(3pm) πŸ’– go forth and cache responsibly πŸŽ€πŸ¦‹πŸ’…

πŸ“¦ where this page comes from