AndyJarrett

ColdFusion 9 caching example

Sometimes with the new/updated features you don't get a chance to implement them right away. Well today I was working on a pulling in feed when I figured I finally had a good use-case to check out the updated caching enhancements in ColdFusion 9.

For this site I was working on I needed to pull in an RSS feed but HTTP calls are slow as there are usually factors outside of your control. The ColdFusion caching functions allows some nice control over what is cached, how often the cached is refreshed, and even when to drop it completley via the following two parameters:

  1. time span ( when we need to re-cache the item )
  2. idle/drop time ( When to drop it from memory when it hasn't been accessed for X amount of time )

For HTTP calls these parameters are perfect. We all want real-time but when is a feed updated that regulary so we can set the timespan to cache the feed for 30-60min. Idle time just means we can free up space after a day or so if the page/cache is not called.

My code below is nothing exciting but it just gives one tiny example of a real world use case. I have wrapped the sample code with a CFTIMER tag so you can visually get an idea of the performance gains acheived. I was seeing response times of 1478ms pre-cache drop to 23ms post-cache, so quite a significant saving to be had.

// My twitter feed twitterFeed = "http://twitter.com/statuses/user_timeline/6203362.rss"; //arrayContains is CaSe SeNsAtIvE and cachePut puts //the reference in in UPPERCASE if( structKeyExists( url, "reload") OR not arrayContains( cacheGetAllIds(), "MYTWITTERFEED" ) ){ feedQry = new feed().read(source="#twitterFeed#"); // After 30 minutes the object is re-cached on // next call. cacheTimeSpan = createTimeSpan( 0,0,30,0); // After 1 day the object is flushed from the //cache if it is not accessed during that time. idleTimeSpan = createTimeSpan( 1,0,0,0); // Put it in cache cachePut( "myTwitterFeed", feedQry, cacheTimeSpan, idleTimeSpan); } else{ feedQry = cacheGet( "myTwitterFeed" ); } writeDump( var=feedQry.name.item, top=3);