Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memcache invalidate entries according to a pattern?

Is there a way to invalidate entries in memcache according to a wildcard key?

So if I have the following memcache keys:

data/1
data/2
data/3

Is there a way I can invalidate those keys with something like data/*? It would be extremely helpful to clear out a bunch of stale data in one swoop.

like image 803
Kekoa Avatar asked Jul 29 '09 18:07

Kekoa


2 Answers

The best way is to provide a versioning key when creating your memcache key. We do this by providing a single function/method for creating a key on our system.

$var1 = 123;
$var2 = 456;
$cacheKey = makeKey('monkeyInfo', $var1, $var2, ...);

makeKey() uses the information in the cacheKeyVersions array and returns:

5:monkeyInfo:123:456

Notice the '5' at the beginning. That comes from a hard-coded array of keyNames => versions. So if we want to invalidate EVERY 'monkeyInfo' cache value in the system we simply have to change that number to 6 in the array. From then on the same call will be looking for

6:monkeyInfo:123:456

Here is an example of what the key version array might look like. The 'makeKey()' call simply looks into this array to get the version number for any given key.

$cacheKeyVersions = array(
    'monkeyInfo'   => 5,
    'zebraInfo'    => 2
);

You could do all sorts of things to make the implementation match your needs, but that's the basic gist of it.

like image 196
conceptDawg Avatar answered Oct 07 '22 11:10

conceptDawg


memcached does not support namespaced deletes.

The official wiki has a suggestion on how to work around it:

like image 40
Gavin M. Roy Avatar answered Oct 07 '22 10:10

Gavin M. Roy