Multiple caches in Memcached

caching, java, memcached

Solution

Typically, this sort of behavior is achieved in memcached via namespacing. Within a single memcached instance, one maintains multiple namespaces, each of which represents a different cache. However, memcached doesn't natively support namespaces - instead, memcached namespaces are emulated by prefixing keys with a namespace identifier (e.g., `memcachedClient.get('products.top10')`). Some memcached clients, like the Python GAE memcached client, abstract this behavior for you. However, xmemcached does not, as far as I can tell.

You are left with two options.

- Manually prefix each key you work with.

- Write a thin wrapper around `XMemcachedClient` with two changes: it has a `String namespace` member that serves as the prefix value, and it overrides `get0()` to apply that prefix. This is a bit dangerous as it relies on the current XMemcached implementation.

Problem

I am migrating caches from EhCache to Memcached. With only 1 Memcached instance, is there a way to have multiple caches (as in EhCache)? For example, I want to have a "Users" cache, a "Products" cache, etc... The main reason for that is to be able to monitor and configure each cache separately, and be able to clear them separately too.

Original source