6 Sep 2009

Caching CFFEED

This post is a continuation of my previous Returning A Twitter RSS Feed As A ColdFusion Query Object post.

To improve application performance it would be useful to be able to cache the qryGetTweets query so a call to the Twitter website is not made for every page request. The following code uses Ray Camden's Example of simple caching of RSS Items code to do this.

Create an instance of the foo object (containing the getTweets function)

<cfset foo = CreateObject( "component", "model.foo" ) />

Set the number of minutes for which the qryGetTweets query will be cached

<cfset cacheMinutes = 60 />

Set your unique Twitter account ID

<cfset twitterID = 19525191 />

If twitterFeedCache (containing the qryGetTweets query) is not in the application scope or the cache has expired call the getTweets function

<cfif !StructKeyExists( application, "twitterFeedCache" ) or DateDiff( "n", application.twitterFeedCache.created, Now() ) gt cacheMinutes>
    <cflock scope="application" timeout="60" type="exclusive">
        <cfset application.twitterFeedCache = {} />
        <cfset application.twitterFeedCache.data = foo.getTweets( id=twitterID ) />
        <cfset application.twitterFeedCache.created = Now() />
    </cflock>
</cfif>