Category Archives: memcached

Storing complex objects in memcached on Railo


Lately I have been doing a lot of research into making sites run efficiently and to a larger extent, load  more quickly.  Yesterday I installed memcached and had it up and running on a test server.  Once the memcached daemon is installed and ready to go you will just need to install a java client that will work for Railo.  My friend Gabe wrote this post that covers what is required to get this up and running on an ACF server.  Getting it running on Railo is little different, just extract the jar files for the Java memcached client into the directory that contains your railo.jar file.

I had a simple proof-of-concept application up quickly, I was able to set a string value in the cache and pull it back from the cache easily.  Things got a little bit bumpy when I tried to store a complex object in cache.  The result coming back from the cache set was coming back as true which would indicate that the object was successfully set in cache.  When I tried to get the object back from cache and dump it, it always returned a null value.  Logging into memcached through telnet I could see there actually was a value stored for the key but it was not returning.

Since I knew I could store simple values with no problem I decided to take the path of least resistance.  Using the Railo serialize() function I could convert complex objects to a string representation and insert it into the cache.  When I pull the value out of cache I evaluate() it and return the object value.  Since I would end up creating a facade for setting/getting objects in cache this is not really an issue.  I know ACF handles this without the need for a work around so it just left me scratching my head.  I would imagine the difference is how Railo and ACF implements the data types, but I have not had time to verify this although if I have some free time this afternoon I intend to look in to this.

Here is a code sample I wrote to get this going.  Basically it is the same as Gabe’s code with some changes to make it work with Railo.

<cfscript>
 serverlist = "127.0.0.1:11211";
 serverList = serverlist.split(",");
 pool = createObject("java","com.danga.MemCached.SockIOPool");
 pool = pool.getInstance();
 if(not pool.isInitialized()){
 pool.setServers(serverList);
 pool.initialize();
 poolInit = pool.isInitialized();
 }

 memcached = createObject("java", "com.danga.MemCached.MemCachedClient");
 someData = queryNew('a, b');
 queryAddRow(someData, 1);
 querySetCell(someData, 'a', 'apple');
 querySetCell(someData, 'b', 'orange');
 dump(memcached.set("someData", serialize(someData)));
 dump(evaluate(memcached.get("someData")));
</cfscript>
Advertisements