I've been working on a complex project using a and distribuited application that requires caching SQL queries: since I've been using iBatis framework, I'd like to use memcached - sysadmin requires it - as caching engine. Is it possible? If yes, does anyone know existing solutions/implementations? I already know OSCACHE works also in cluster, but I'd like to know if using the existing architecture is possible, before switching to a new one. Many thanks in advance!!!
Interesting question!
iBatis returns one or more JavaBeans, which in turn may contain nested Lists of JavaBeans. A JavaBean is just a Java object that adheres to certain simple conventions, one of which is that it implement the Serializable interface. If it does, you can serialize a JavaBean structure into a String, and deserialize that String back into a deep copy of the original JavaBean structure.
So let's assume you ensure all your result objects are declared to "implement Serializable". JavaBeans have such a simple structure that the default Java object serialization/deserialization mechanisms don't need to be overridden, which is good.
These serialized Strings are the values you put into your memcached cluster's distributed hash map. In each of your Java methods that runs a query and returns its results, you first lookup the existing result in memcached, and if it is there and hasn't expired, you deserialize it into the JavaBeans that (presumably) your query would have returned. If the query result is not found in memcached, then you query the database through iBatis, but before you return the result, you serialize it into a String and store that value in memcached.
The next question is what to use for the memcached query result keys. Something like
YourIbatisQueryName + ":" + FirstParameterValue + ":" + SecondParameterValue
should work (eg, "SelectStackOverflowReputation:Simone:Tripodi").
You're almost finished. The final step is to figure out how long a query result can be cached without becoming invalid. Perhaps you can establish a different expiration time for each query, or maybe you need a manual cache invalidation mechanism. Caching query results even for just a few minutes can have very strong effects on your application's scalability.
Note: A variation on this approach is to not use the default Java serialization, but use XML, or JSON, or some other format. If you choose XML or JSON, look into a serialization framework like XStream to serialize/deserialize your JavaBeans into XML Strings and back again.