Log in

No account? Create an account
Object caching with ColdFusion - Nick [entries|archive|friends|userinfo]

[ website | gagravarr.org ]
[ userinfo | livejournal userinfo ]
[ archive | journal archive ]

Object caching with ColdFusion [Nov. 28th, 2004|06:15 pm]
Recently, Tom has extended the cf_accelerate tag, so you can use file based caches. This allows you to easily cache a large number of pages / page fragments, without hitting memory usage limits (as in memory caching tends to), by nicely handling writing to/fetching from files.

This is quite handy, but not in all cases. It works well for web pages, semi-dynamic menus etc, but not for database driven web apps. For these, the bulk of your page time is on the query. That same query (with parameters) might be shared with a bunch of pages, and different bits of a page might need different caching times. So, I was challenged to try to find a way to cache ColdFusion objects on disk.

I immediately turned java's object serialisation, since ColdFusion uses java under the covers. As it happened, I was in luck, and Macromedia had everything worked out for this to work easily.

Firstly, all the key objects (structures, queries etc) are serialisable. That means you can use ObjectInputStream and ObjectOutputStream on them as is, and everything works. Chuck in FileOutputStream and FileInputStream, and you're away.

The second nifty thing is how ColdFusion handles objects coming back from the java layer. I was stressing about how to handle the casting of a generic object (from readObject) back to the appropriate ColdFusion object, since JavaCast doesn't work for complex types. Then, I discovered ColdFusion just did it all for me! When I did , ColdFusion automatically casts foo to the appropriate object. Very handy.

I haven't had a chance to write a nice caching interface for objects, but I'm told Tom will do a cf_accellerate like tag for it. In the mean time, this component should do you:

<cffunction name="cacheObject"
returntype="void" access="public"
hint="Caches a given ColdFusion object">
	<cfargument name="object">
	<cfargument name="filename" type="string">

	<cfset fos = CreateObject("java","java.io.FileOutputStream")>
	<cfset fos.init(JavaCast("string",filename))>
	<cfset oos = CreateObject ("java","java.io.ObjectOutputStream")>
	<cfset oos.init(fos)>
	<cfset oos.writeObject(object)>

<cffunction name="fetchObject" access="public"
hint="Fetches a given Object">
	<cfargument name="filename" type="string">

	<cfset fio = CreateObject("java","java.io.FileInputStream")>
	<cfset fio.init(JavaCast("string",filename))>
	<cfset oio = CreateObject("java","java.io.ObjectInputStream")>
	<cfset oio.init(fio)>
	<cfset o = oio.readObject()>
	<cfreturn o>