Google App Engine: Memcache – How can you create a multiple Memcache?

(http://code.google.com/appengine/docs/java/memcache/overview.html)

Google App Engine provides Memcache as a part of App Engine. Memcache implements the JCache interface (javax.cache).

The App Engine provides MemcacheService and implementation of jCache API. There are a lot of useful features that the jCache does not provide.

Here is how one can create a multiple Memcache in App Engine.

MemcacheService cacheA = MemcacheServiceFactory.getMemcacheService();

cacheLock.setNamespace( “A” );

MemcacheService cacheB = MemcacheServiceFactory.getMemcacheService();

cacheTxnLocked.setNamespace( “B” );

MemcacheService cacheC = MemcacheServiceFactory.getMemcacheService();

cacheAllTxns.setNamespace( “C” );

Once you create the Memcache using the MemcacheServiceFactory, you need to set the Namespace. The “Namespace” causes the cache to be different.

So, if you do not set the “Namespace” on the cache, then all the cache that you get from the MemcacheService will be the same.

A pattern to use Memcache in the App Engine (or in any application server) is to use a Singleton to hold the cache. Singleton allows to initialize the different caches and works as a Facade to the Memcache.

This design has many useful features. Few of those are:

  • hides the actual implementation of Memcache which allows to change cache without impacting the user of the cache.
  • allows data access objects to be cached such that the cached persistence objects are managed by same persistence context.