Caching Enhancements in ColdFusion 9 – Part 9: Dependent Template Caching

Welcome to Part 9 of my series on Caching Enhancements in ColdFusion 9. Today we're going to cover something called dependent template caching. Strange name, I know. If you remember back from Part 7, we said that by default, when you cache a web page or page fragment with the cfcache tag, that page/fragment goes into the cache and is retrieved for any subsequent visits to that page. The same content is returned for everyone. We also covered a method for caching pages based on unique URL parameters such that different versions of the same page (say a product display page) would be cached and retrieved from the cache based on URL parameters. But what about page/page fragments that vary based on other variables that aren't passed in via URL? This is where dependent template caching comes in.

Dependent template caching allows you to specify a variable or list of variables to "watch" for changes. If the value of one of these variables changes from the first page or fragment that was cached, ColdFusion will create a new variant for the page/fragment and store that in the cache as well. This is all handled by using the new dependsOn attribute of the cfcache tag in ColdFusion 9. If you are reading this and wondering where this might be useful, you aren't alone. When I first read about this feature in the ColdFusion docs, I misunderstood the intent of the attribute and how it's supposed to work. Here's what the Coldfusion 9 docs have to say about dependsOn:

A comma separated list of variables. If any of the variable values change, ColdFusion updates the cache. This attribute can take an expression that returns a list of variables.

I think the key to the misunderstanding people have about this feature is in the part that says "If any of the variable values change, ColdFusion updates the cache." To me, updating the cache means replacing an old/expired/changed value with a new one. It's a one for one swap of items in the cache. Out with the old and in with the new. But this isn't what happens when you use dependsOn. What the docs should say is that when a variable value changes, ColdFusion creates a new entry in the cache for the changed item so that both the original page/fragment as well as the new page/fragment are now in the cache. Here's a quick example to illustrate how this works:

view plain print about
1<cfset y=true>
2
3<cfflush>
4<cfloop index="x" from="1" to="5">
5<cfif x is 3>
6    <cfset y=false>
7<cfelse x is 5>
8    <cfset y=true>
9</cfif>
10
11
12<cfset sleep(1000)>
13<cfflush interval="10">
14<cfcache action="serverCache" dependsOn="#y#" stripWhiteSpace="true">
15<cfoutput>
16I'm cached dynamic data: #now()# <br/>
17</cfoutput>
18</cfcache>
19
20<!--- dump what's in the template cache --->
21<cfdump var="#getAllTemplateCacheIDs()#">
22</cfloop>

If you run this code, you should see something that looks like this:

What this code does is create a page fragment and cache it within a loop. The cfcache tag is set to watch a variable called y for changes. The value of y is initially set to true. There's also some conditional code in the loop which waits for the third and fifth iterations of the loop to fire. We'll get to that in just a moment. For now, let's step through each iteration of the loop and discuss what's happening. During the first iteration of the loop, the fragment is added to the cache. During the 2nd iteration of the loop, the fragment is pulled from the cache and displayed. During the third iteration of the loop, the value of x is 3 and our cfif statement fires, updating the value of y to false. Because y is the value we set to watch in the dependsOn attribute of our cfcache tag and it has now changed from true to false, this signals ColdFusion to go ahead and cache the version of the loop output we're now on for iteration 3 of the loop. This is where we end up with a 2nd fragment in the cache, not an update to the existing fragment in the cache. The fourth iteration of the loop also displays the second cached fragment since the value of y is still false. For the fifth and final iteration of the loop, our conditional code within the loop fires again. This time it sets y back to false, a value which we already have a fragment stored in the cache. ColdFusion knows to go grab the fragment for false from the cache and displays it.

There's one other thing to note in here. I didn't think to include this in any of the previous posts on the template cache so I've decided to add it here. If you look at the end of the cfcache tag in our example, you'll notice a parameter you probably haven't seen before: stripWhiteSpace. This is an optional parameter that only works if you are using the template cache to cache page fragments. Setting it to true (it's false by default) tells Coldfusion to strip any unnecessary whitespace from the fragment before storing it in the cache.

While this is a good example of the mechanics of dependent caching, it's not really a practical example. For that, let's consider a real world example where you would want to make use of dependent caching. Say you have an application that requires authentication. The main landing page for the application is personalized based on who is logged in. In this case, you can't cache a single version of the main page as you wouldn't want it to say "Hello Tom" when Mary logs in. Sure you could solve this by passing the username along in the URL, but you probably don't want to do that – who wants to deal with all of the extra validation code to make sure someone doesn't go and change that URL variable to someone else's username. No, in this case, you would probably be using session variables in your application to maintain persistence, and session variables are a perfect use case for dependent caching. Here, we could set dependsOn to watch something that uniquely identifies a user and when that changes (a different user is logged in), the personalized version of the page for them could be added to the cache. Let's take a look at some simple code that implements this idea. The first thing we'll need is an Application.cfc file to setup session management and handle security basics for us:

view plain print about
1<cfcomponent output="false">
2    <cfset this.name = "dependentCaching" />
3    <cfset this.sessionManagement = true>
4
5 <cffunction name="onRequestStart" eeturntype="boolean" output="false">
6     <cfif StructKeyExists( URL, "logout" )>
7         <cfset this.onSessionStart() />
8     </cfif>
9
10     <cfreturn true />
11 </cffunction>
12
13    <cffunction name="onRequest" returnType="void" output="true">
14     <cfargument name="Page" type="string" required="true">
15
16        <cfif session.loggedIn>
17            <cfinclude template="#arguments.Page#">
18        <cfelse>
19            <cfinclude template="login.cfm">
20        </cfif>
21
22        <cfreturn />
23    </cffunction>
24
25    <cffunction name="onSessionStart" returnType="void" output="false">
26     <cfset session.loggedIn = false>
27    </cffunction>
28
29</cfcomponent>

This code gives our application a name and turns on session management. If also has an onRequestStart() method that looks for a URL variable called logout, and if it finds one it fires off the onSessionStart() method, effectively logging the user out be changing the value of session.loggedIn to false.

The onRequest() method handles the check to see if a user is authenticated for a requested page. If session.loggedIn is true, the page they were requesting is included. Otherwise, we assume that the user is not logged in and include the login form instead.

The onSessionStart() method fires at the beginning of a user's session and sets their logged in status to false by default.

Remember that this is just a simple example and for that reason does not contain all of the code you would use to implement something like this in real life (validation checks, error handling, etc.).

The next file we need is our login.cfm page:

view plain print about
1<cfif isDefined('form.submit')>
2 <cfset session.loggedIn = true>
3 <cfset session.userName = form.username>
4
5 <!--- send the user back to the main page --->
6 <cflocation url="index.cfm" addtoken="false" />
7
8<cfelse>
9
10 <cfoutput>
11 <form method="post">
12 Name: <input type="text" name="userName"><br />
13 Password: <input type="password" name="password"><br />
14 <input type="submit" name="Submit" value="Submit">
15 </form>
16 </cfoutput>
17</cfif>

This page is just a simple login form. It firsts checks to see if it was called via a form submit, and if so sets the value of session.loggedIn to true. It also sets another session variable to hold the user's username. After the variables are set, the user is redirected to the main landing page for the application (index.cfm) Again, if this were a real application we would have an actual login check here but for the purposes of this example we're just assuming that any username/password combo is valid.

If the user arrived at the page directly from the onRequest() method of our Application.cfm page, we know that they have not yet logged in so we display a login form for them. When they submit this, the page submits to itself and the code we previously discussed fires, logging the user in and redirecting them to the main application page. Here's the code for the main index.cfm page:

view plain print about
1<cfcache action="serverCache" timespan="#createTimeSpan(0,0,5,0)#" dependsOn="session.username">
2<cfoutput>
3Welcome #session.username#
4
5<p>This is your personalized page.</p>
6
7<p>Timestamp: #timeFormat(now(), 'hh:mm:ss')#</p>
8
9<p><a href="index.cfm?logout=true">Logout</a></p>
10</cfoutput>

There's not a whole lot going on here. All we do is set a cfcache tag at the top of the page telling ColdFusion that we want to cache the contents of the entire page. A timespan of 5 minutes is set just to keep the example from staying in the cache forever. Notice we also set dependsOn=session.username". This is where the magic happens. What we've done is told ColdFusion is that every time a different user tries to call this page, it should first check the cache to see if there's already a page stored for this user and if so, grab and use that version. If not, it should generate a new version of the page and cache that value for later use.

If you want to see this in action, go ahead and open the index.cfm page in your browser. You should be redirected to the login form. You can enter anything you like for the username and password. Once you submit the login form, you should be redirected to a personalized version of the index.cfm page. Note the value of the timestamp.

Now go ahead and click on the logout link. This will clear your session and cause the login form to display again. Try logging in using a different username this time. After submitting, you'll again be redirected to a personalized version of index.cfm.

Logout again and repeat the process again but this time use the username you entered the first time. When you submit and are taken to the index.cfm page you should notice that the value of the timestamp is the same as the first time you logged in as this user. This is because ColdFusion saw that session.userName changed and found a page in the cache that corresponded to the username you logged in with (the username becomes part of the key for the page in the template cache). If you want to see that there are two distinct pages in the cache, just create a new ColdFusion page in the same directory as the rest of your application and add dump the template cache using this code:

view plain print about
1<cfdump var="#getAllTemplateCacheIds()#">

You'll end up with something like this:

As you can see, each individual user has their own copy of the index.cfm page in the cache thanks to dependsOn.

I hope these examples were straightforward and useful enough to demonstrate the usage and power of dependent caching in ColdFusion 9. This is the last post on the template cache I have planned for the series. In Part 10, we'll start to take a look at the object cache in ColdFusion 9 before moving on to more advanced topics.

Caching Enhancements in ColdFusion 9 - Part 8: Expiring and Flushing Items in the Template Cache

When using the template cache in ColdFusion 9, you have two main options for getting pages and page fragments out of the cache – time based expiry and flushing. This blog post covers both. You should not that all of the examples here cache full pages. In most cases, the techniques discussed can be applied equally to page fragments.

Expiring Items in the Template Cache

It's also possible to set expiry periods for items in the template cache. Here, you have two optional parameters built in to the cfcache tag to help you expire pages and fragments from the cache based on time periods. The two parameters you can use are idletime and timespan. Idletime lets you specify a period of time after which to flush the cache if the cached item has not been accessed. In other words, if the cached item hasn't been accessed in the time period specified by idletime, the item will be removed from the cache. Here's an example that caches a page and will flush it after 30 seconds of inactivity:

view plain print about
1<cfcache action="serverCache" idletime="#createTimeSpan(0,0,0,30)#">
2
3<cfoutput>
4I'm dynamic. The time is currently #timeFormat(now(),'hh:mm:ss')# </cfoutput>

If you run this code and then run it again, you'll see that the timestamp for the page is cached. Now wait for 30 seconds or so and reload again. You should see that the time has updated.

The timespan parameter lets you specify a period of time after which the cached item should be flushed regardless of whether it's ever been accessed or not. This basically lets you say "keep this page in the cache for 30 seconds". Here's an example:

view plain print about
1<cfcache action="serverCache" timespan="#createTimeSpan(0,0,0,30)#">
2
3<cfoutput>
4Currently #timeFormat(now(),'hh:mm:ss')#
5</cfoutput>

This code sets a timespan of 30 seconds. If you run the code then run it again, you'll see that the timestamp gets cached. Go ahead and keep hitting the reload button on your browser every few seconds. After 30 seconds have gone by, the timestamp will update as the old content is flushed from the cache.

Flushing Items from the Template Cache

In addition to time based expiry, you can also manually flush both pages and page fragments from the template cache using the cfcache tag. Here's an example:

view plain print about
1<cfcache action="flush">

There are a couple of things to note here. First, when you call this code, it flushes all templates in the template cache for your application, not just the page you call it from. Let me repeat that. Using the cfcache tag with action="flush" causes the template cache to flush all of the content for the current application. You need to be very careful using this as it's possible that on a high traffic site with a large template cache you could bring your server down when hundreds or thousands of requests hit at the same time for uncached data, causing your system to queue up requests while it's busy rebuilding the cache. In most cases what you'll want to do is to flush a single page or perhaps a group of related pages from the template cache.

So, how do you go about flushing a single page or a group of related pages from the template cache? There's another parameter of the cfcache tag you can use called expireURL just for this purpose. Let's consider an example of how we would use this:

view plain print about
1<cfif isDefined('URL.productID') AND isDefined('URL.flush')>
2    <cfcache action="flush" expireURL="*.cfm?productID=#URL.productID#">
3</cfif>
4
5<cfparam name="URL.productID" default="0">
6
7<cfcache action="serverCache" usequerystring="true" timespan="#createTimeSpan(0,0,5,0)#">
8<cfoutput>
9Welcome to the page for product ID #URL.productID#<br />
10Timestamp: #timeFormat(now(), 'hh:mm:ss')#
11</cfoutput>

Go ahead and run this example in your browser. You should have something on your screen that looks like this:

view plain print about
1Welcome to the page for product ID 0
2Timestamp: 03:40:11

Reloading the page should return the same timestamp over and over as the template is cached after the first call. Now try adding the URL parameter ?productID=72 to the URL string in your browser and reload the page a few times to get the new version of the page into the cache. Try changing the value of productID a few more times, each time reloading the page so that we get a handful of pages in the template cache. Now try dumping the contents of the template cache by running this code in a separate ColdFusion file:

view plain print about
1<cfdump var="#getAllTemplateCacheIds()#">

You should see a bunch of different entries – one for each unique productID you provided in the URL. Now go ahead and call the code we've been working with for this example, only this time append ?productID=72&flush to the URL. Go ahead and reload the page with those URL parameters a couple times. Notice the timestamp updating each time you reload? That's because passing in the URL parameter flush calls the ColdFusion page to call the cfcache tag with expireURL="*.cfm?productID=#URL.productID#". The expireURL parameter lets you specify a wild carded URL pattern such that only pages that match the pattern get flushed. This allows you to get as generic or as specific as you want in determining exactly what pages to flush. In this case we're telling ColdFusion to go ahead and flush any cached .cfm pages that have the URL parameter ?productID equal to the value that we pass in on the URL.

If you dump the contents of the template cache you'll notice that there's still an entry for the item(s) we just flushed. That's because the code in the example we've been running repopulates the cache immediately after the flush. If you didn't want the cache repopulated immediately after flushing the content, you could just as easily locate the code to flush the cache elsewhere and just remove the item.

If you want to remove a group of related pages from the cache, say all of the pages that have a productID, you could modify the code to wildcard the productID parameter like so:

view plain print about
1<cfcache action="flush" expireURL="*.cfm?productID=*">
2
3<cfdump var="#getAllTemplateCacheIds()#">

This should result in the removal of all pages from the cache that have a productID URL parameter. Note that if you run this right now in ColdFusion 9.0 it will not work. There is a bug in ColdFusion 9.0 with the wildcard feature. If you put the flush code in a separate template and run it multiple times, what you'll see is that one page at a time is flushed from the cache instead of all of the pages that match the URL pattern at once. Credit goes to Aaron West for catching this bug.

That about wraps up everything I have to say about expiring and flushing pages and page fragments from the template cache. In Part 9 we'll talk about one last feature of the template cache – Dependent Caching.

Caching Enhancements in ColdFusion 9 - Part 7: Using the Template Cache

In Part 5 of this series, we introduced the template cache with a quick example that showed how to cache page fragments. As we mentioned then, the template cache can be used to cache page fragments as well as entire web pages. This post is broken up into three sections that explore the three typical use cases of the template cache: Caching entire wen pages, caching entire web pages with url parameters and caching page fragments.

Caching Entire Web Pages

To cache an entire web page, simply place a single cfcache tag at the top of you page. Here's an example:

view plain print about
1<cfcache action="serverCache">
2
3I'm some text on a page<br />
4
5<cfoutput>
6I'm dynamic. The time is currently #timeFormat(now(),'hh:mm:ss')# <br />
7</cfoutput>
8
9I'm some more test on a page

With an open cfcache tag at the beginning of the page, this code tells ColdFusion to go ahead and write the entire page to the template cache. If you haven't modified your cache configuration from the default ColdFusion install, this item will live in the cache for 24 hours (86400 seconds) unless you restart your JVM by restarting your ColdFusion server or you manually flush the cache first, which you can do by using the cfcache tag with action="flush" which we'll talk about in the next part of this series.

As I mentioned in Part 5 of this series, the ColdFusion template cache acts as a black box. You don't really get to see how it magically does gets and puts of your content or how it generates keys for the data going into the cache. What I didn't mention before is that there's an undocumented function in ColdFusion 9.0 called getAllTemplateCacheIDs() that will show you all of the keys for items that ColdFusion puts in the template cache. There isn't really a lot you can do with this information since neither the cfcache tag nor any of the cache functions allow you to specify a key for items in the template cache. However, the function is useful for showing how ColdFusion handles general ColdFusion pages, pages with URL parameters and page fragments differently within the cache.

When ColdFusion takes a regular old ColdFusion page and caches it in the template cache, it generates a unique key for it based on the URL and a UUID appended to it. Here's an example of a file called cache_entire_page.cfm:

view plain print about
1<cfcache action="serverCache">
2
3<cfoutput>
4I'm dynamic. The time is currently #timeFormat(now(),'hh:mm:ss')# </cfoutput>

If you run this page, ColdFusion puts it in the template cache as you would expect. To see the key that ColdFusion automatically generates for it, create a new ColdFusion page with this code in it:

view plain print about
1<cfdump var="#getAllTemplateCacheIds()#">

If you run that newly created page, you should see a dump of all the keys in the template cache for your application. It should look something like this:

Caching Pages with Unique URLs

By default, URL parameters for ColdFusion pages stored in the template cache are ignored. If you want to see this in action, try adding ?id=10 to the URL of the cache_entire_page.cfm file we used for our previous example. After you've added the URL parameter and reloaded the page, go ahead and dump the contents of the template cache again. What you'll notice is that it contains the same exact key as the page without the URL parameter. Obviously this isn't good if your application has what it considers to be unique pages that need to be cached individually based on URL parameters. Luckily, the cfcache tag gives you a way to handle this. All you need to do is add useQueryString="true" to your cfcache tag and that will tell ColdFusion to treat pages that have URL parameters as unique pages when it caches them. Go ahead and save this code as a new ColdFusion page:

view plain print about
1<cfparam name="URL.productID" default="0">
2
3<cfcache action="serverCache" usequerystring="true">
4<cfoutput>
5Welcome to the page for product ID #URL.productID#<br />
6Timestamp: #timeFormat(now(), 'hh:mm:ss')#
7</cfoutput>

Now try calling this page with no URL parameter passed to it. Right after you've done that, append ?productID=55 to the URL and call it again. Once you've done this, run the sump of all the keys in the template cache and you should have output that looks like this:

What you should notice right away is that there are now two new keys being returned for the page you just called twice. The first key looks just like the key from our last example. It contains just the template name and a UUID. The other key, however, contains something new. In addition to the URL for the template and the appended UUID, it also contains the query string as part of the key name. As you can see, by using the useQueryString parameter of the cfcache tag, we've instructed ColdFusion to treat pages with URL parameters as unique when it places them in the template cache.

Caching Page Fragments

When ColdFusion caches a page fragment, it uses a combination of the page's file name as well as the position of the actual code block that's surrounded by cfcache tags in your ColdFusion file. Each page fragments gets its own entry in the cache since fragments can be independently expired or flushed from the cache. Consider the following example:

view plain print about
1<cfcache>
2This is a fragment
3</cfcache>
4
5<cfcache>
6<cfoutput>
7And so is this #now()#
8</cfoutput>
9</cfcache>
10
11<cfdump var="#getalltemplatecacheids()#">

If you execute this, you'll get some output as well as a dump of all of the cached items in the template cache. At this point, there are two items in the cache:

Now say you weren't happy that the two lines of output on your page were all run together and you wanted to put a line break between each one. You might modify your code and add in a simple paragraph tag or line break like so:

view plain print about
1<cfcache>
2This is a fragment
3</cfcache>
4
5<p>
6
7<cfcache>
8<cfoutput>
9And so is this #now()#
10</cfoutput>
11</cfcache>
12
13<cfdump var="#getalltemplatecacheids()#">

Go ahead and run the code once you've inserted the

tag. What you'll now see is that you have three items in the cache:

What's happening is that ColdFusion is using the position of the code in your page as part of the ID for the cached item. When you inserted the

tag, the position of the fragment you cached also changed by moving down a few lines, and ColdFusion assumed you had added a new page fragment that you wanted to cache.

This may or may not be a big deal to people as CF will still pull the correct cached item every time. The gotcha is that if you have a lot of caching going on, and you're making a lot of changes in a development environment, it's possible to fill your cache up with a lot of junk pretty quickly – just something to be aware of with the template cache when working with page fragments.

Now that we've covered the basics of the template cache, keep an eye out for my next post where I'll cover the ins and outs of updating items in the template cache including techniques for time based expiry, cache flushing, and dependent caching.

Caching Enhancements in ColdFusion 9 - Part 6: Configuring Caches and Working with ehcache.xml

In Part 5 of this series, we mentioned that Ehcache could be configured at runtime via ColdFusion code as well as by using an XML configuration file called ehcache.xml.

On a Java EE install of ColdFusion 9, you can find the ehcache.xml file located here:

/JRun4/servers/servername/cfusion-ear/cfusion-war/WEB-INF/cfusion/lib

There are two main sections of the file you need to be concerned with for basic configuration. The first section you should take a look at is the DiskStore configuration:

view plain print about
1<diskStore path="java.io.tmpdir"/>

This tag tells Ehcache where it should write cache files if you have the cache configured to overflow to disk or to persist to disk. We'll get into the specifics of those options, but for now it's important to know that by default Ehcache will use your Java temp directory to store cache files if it is configured to do so. On Windows, the Java temp directory is located in c:/windows/temp. You can change the value here to any drive/directory on your system if you wish to use a location other than the Java temp directory.

The next section to take a look at comes at the end of the ehcache.xml file. Skip on down to the very end where you should see a block of XML that looks like this:

view plain print about
1<defaultCache
2 maxElementsInMemory="10000"
3 eternal="false"
4 timeToIdleSeconds="86400"
5 timeToLiveSeconds="86400"
6 overflowToDisk="false"
7 diskSpoolBufferSizeMB="30"
8 maxElementsOnDisk="10000000"
9 diskPersistent="false"
10 diskExpiryThreadIntervalSeconds="3600"
11 memoryStoreEvictionPolicy="LRU"
12 />

This block of XML tells ColdFusion how to configure all of the Object and Template caches that are automatically created for your application. When a cache is automatically created, the name for the cache is also automatically created using the convention appnameOBJECT for object caches and appnameTEMPLATE for template caches. Each cache has a number configurable parameters:

  • maxElementsInMemory: Sets the max number of objects that will be created in memory. Once this limit is reached, the cache will either overflow to disk (if overflowToDisk is set to true), or the appropriate eviction policy will be executed against the cache to make enough room for the new item(s) being added.
  • eternal: Sets whether elements are eternal. If eternal is set to true, timeouts are ignored and the element is never expired.
  • timeToIdleSeconds: Sets the time to idle for an element before it expires.
  • timeToLiveSeconds: Sets the time to live for an element before it expires.
  • overflowToDisk: Sets whether elements can overflow to disk when the memory store has reached the maxElementsInMemory limit.
  • diskSpoolBufferSizeMB: Specifies the spool buffer size for the DiskStore, if enabled. Writes are made to the spool buffer before they are asynchronously written to the DiskStore.
  • maxElementsOnDisk: Sets the max number of objects that will be maintained in the DiskStore
  • diskPersistent: Whether the disk store persists between restarts of the Virtual Machine.
  • diskExpiryThreadIntervalSeconds: Specifies the interval (in seconds) between runs of the disk expiry thread.
  • memoryEvictionPolicy: Policy to enforce upon reaching the maxElementsInMemory limit (LRU, LFU, FIFO).

If you make changes to any of these parameters, ColdFusion will apply them to any new caches that it automatically creates. If you have disk persistence or overflow to disk turned on, two files will be written to your file system per cache, an index file and a data file. For an object cache you would get appnameOBJECT.index and appnameOBJECT.data.

If you want to see what properties have been set for your application's cache, you can do so using the cacheGetProperties() function. The function takes a single optional parameter that specifies the type of cache to return the properties for. Options are Template or Object. If you don't specify the cache type to return properties for, ColdFusion returns them for both cache types. Here's an example that dumps the properties for both the default Object and Template caches:

view plain print about
1<cfdump var="#cacheGetProperties()#">

This will result in output that looks like this:

As you can see from the screen shot, the structure keys correlate to parameters form the ehcache.xml file with two notable exceptions. Both diskSpoolBufferSizeMB and diskExpiryThreadIntervalSeconds are not reported on as properties that can be changed programmatically at runtime.

If you wish to change any of these properties programmatically, you can do so using the cacheSetProperties() function. This function takes a single argument – a structure containing all of the properties that should be configured. You can configure any of the following parameters:

  • objectType: Specifies the cache type: Object, Template, or All
  • diskStore: Supposed to specify the location of the DiskStore for disk based caching but this is currently not working as of ColdFusion 9.0.
  • diskPersistent: Whether the disk store persists between restarts of the Virtual Machine. True|False
  • eternal: Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. True|False
  • maxElementsInMemory: Sets the max number of objects that will be created in memory. Integer
  • maxElementsOnDisk: Sets the max number of objects that will be maintained in the DiskStore. Integer
  • memoryEvictionPolicy: Policy to enforce upon reaching the maxElementsInMemory limit: LRU, LFU, FIFO
  • overflowToDisk: Sets whether elements can overflow to disk when the memory store has reached the maxElementsInMemory limit: True|False
  • timeToIdleSeconds: Sets the time to idle for an element before it expires: Integer number of seconds
  • timeToLiveSeconds: Sets the time to live for an element before it expires: Integer number of seconds

Remember, this only applies to caches automatically created by ColdFusion. If a cache doesn't yet exist and you call cacheSetProperties(), ColdFusion will automatically create the cache for you based on whether you are setting properties for an Object cache, a Template cache, or both.

The following code shows how to build the structure of parameters necessary to configure a cache and set the cache properties using the cacheSetProperties() function:

view plain print about
1<cfset myProps = structNew()>
2<!---
3<cfset myProps.diskstore = "c:/temp"> <!--- in the docs, but not currently implemented --->
4--->

5<cfset myProps.diskpersistent = "true">
6<cfset myProps.eternal = "false">
7<cfset myProps.maxelementsinmemory = "5000">
8<cfset myProps.maxelementsondisk = "100000">
9<cfset myProps.memoryevictionpolicy = "LRU">
10<cfset myProps.objecttype = "Object">
11<cfset myProps.overflowtodisk = "true">
12<cfset myProps.timetoidoleconds = "86400">
13<cfset myProps.timetolivesecond = "86400">
14
15Before:
16<cfdump var="#cacheGetProperties("Object")#">
17
18<!--- update the cache properties --->
19<cfset cacheSetProperties(myProps)>
20
21After:
22<cfdump var="#cacheGetProperties("Object")#">

It's also possible to create more caches than just the default template and object caches that ColdFusion creates automatically for you. This can be achieved by defining them in your ehcache.xml file or at runtime using the cfcache tag. To configure a new cache region in your ehcache.xml file, you would do so like this (place this before or after the defaultCache block in your ehcache.xml file):

view plain print about
1<cache
2 name="myCustomObjectCache"
3 maxElementsInMemory="500"
4 eternal="false"
5 timeToIdleSeconds="86400"
6 timeToLiveSeconds="86400"
7 overflowToDisk="true"
8 diskSpoolBufferSizeMB="30"
9 maxElementsOnDisk="10000000"
10 diskPersistent="true"
11 diskExpiryThreadIntervalSeconds="3600"
12 memoryStoreEvictionPolicy="LRU">

As you can see, the only difference between this code and the code for the default cache is that you give the cache region a name using the name parameter.

You should know that neither cacheGetProperties() nor cacheSetProperties() can be used to configure the properties for a custom cache in ColdFusion 9.0. Hopefully this is a feature that will be added in a future version of ColdFusion.

If you want to read from or write to a custom cache, you can only do so using the cfcache tag. Here's an example:

view plain print about
1<!--- attempt to get the artist query from
2 the custom object cache --->

3<cfcache
4    key="myCustomObjectCache"
5    action="get"
6    id="artistQuery"
7    name="getArtists"
8    metadata="myMeta">

9
10<!--- if the item isn't there, it'll return null.
11 In that case, run the query and cache the
12     results and rerun the data from the db instead --->

13<cfif isNull(getArtists)>
14    <cfquery name="getArtists" datasource="cfartgallery">
15        SELECT *
16        from artists
17    </cfquery>
18
19    <cfcache
20        key="myCustomObjectCache"
21        action="put"
22        id="artistQuery"
23        value="#getArtists#">

24</cfif>
25
26<!--- dump the query from cache --->
27<cfdump var="#getArtists#">
28
29<!-- dump the cache meta data --->
30<cfdump var="#myMeta#">

This code is almost identical to the code we wrote in Part 5 where we introduced the object cache (don't worry about the extra metadata we're pulling using cfcache. We'll cover that later). The only real difference is that here we specify a name for our cache in both cfcache tags by defining it in the key attribute. Key allows us to specify a custom name for our cache. If a cache by that name hasn't been configured in your ehcache.xnl file, ColdFusion will automatically create it using the parameters set in the default cache settings. Remember, you can only work with custom caches using the cfcache tag. None of the cache functions in ColdFusion 9.0 allow you to specify the cache name you want to apply the function to. Go ahead and run the code a few times to verify it's pulling from the custom cache.

There's a lot more advanced stuff that can be configured in the ehcache.xml file such as cache clustering. These topics deserve their own posts, which we'll get to soon. For now, thanks for sticking with the series and I hope you've learned a little more about the ins and outs of cache configuration in ColdFusion 9.

Caching Enhancements in ColdFusion 9 – Part 5: Getting to Know Ehcache

In previous versions of ColdFusion (before ColdFusion 9 that is), there were three built-in mechanisms you could for caching – persistent variable scopes, query caching and the cfcache tag. As I mentioned in Part 2 of the series, each of these methods has inherent limitations and generally requires a good deal of additional programming to gain any semblance of control over the actual cache – if that is even possible. In many cases it really isn't practical or even possible to see how much information is stored in one of the aforementioned caching mechanisms. All of this changes with the introduction of Ehcache as the underlying cache provider in ColdFusion 9. Five parts into this series, and I just realized I've mentioned Ehcache several times but I never really took the time to talk about what exactly it is and how it's been implemented in ColdFusion 9.

The Ehcache project was started by a gentleman named Greg Luck. Ehcache can best be described as "... a widely used Java distributed cache for general purpose caching, Java EE, and lightweight containers." Caches are implemented as key-value stores, much like a ColdFusion structure. One important feature of an Ehcache cache is that it can be persisted to memory, disk, or both. Optionally, memory caches can be configured to survive JVM restarts (or in our case, ColdFusion server restarts). Caches can be configured via an XML configuration file named ehcache.xml or programmatically at runtime. Ehcache ships as a JAR file and runs in-process within an application server's JVM. In the case of ColdFusion 9, the JAR file and the XML file used to configure it (ehcache.xml) are both located in:

/JRun4/servers/server_name/cfusion-ear/cfusion-war/WEB-INF/cfusion/lib

ColdFusion 9 implements three types of caches using the Ehcache engine: Template Caches, Object caches and Hibernate Caches. Each of these cache types has their own use cases and we'll cover them in depth in future blog posts. For now, here's a quick summary of what each cache type is and generally what it's used for.

The template cache is designed for caching entire web pages as well as page fragments (sections of web pages). You shouldn't confuse this with the template cache mentioned in the ColdFusion Administrator. That template cache is concerned with compiled ColdFusion templates stored in memory. It's unfortunate that this dual use of the term "template cache" exists in ColdFusion so you need to be aware of which type of cache is being referred to when you see template cache mentioned. In terms of the Ehcache template cache implementation in ColdFusion 9, it's a fairly automatic process with ColdFusion handling the bulk of the work managing keys, cache gets/puts and expiry/eviction from the cache. Working with the template cache is done exclusively using the cfcache tag. Here's a very basic example:

view plain print about
1<cfoutput>
2I'm real-time dynamic data #now()# <br/>
3</cfoutput>
4
5
6<cfcache action="serverCache">
7<cfoutput>
8I'm cached dynamic data: #now()# <br/>
9</cfoutput>
10</cfcache>
11
12<cfoutput>
13I'm also real-time dynamic data #now()# <br/>
14</cfoutput>
15
16<cfcache action="serverCache">
17<cfoutput>
18I'm cached dynamic data too: #now()# <br/>
19</cfoutput>
20</cfcache>

In this code, the first section displays the current date/time. The second section uses the cfcache tag with action="serverCache". This action specifies that we want to use server side caching (Ehcache) and is now the default action in ColdFusion 9. To cache a fragment of code in a ColdFusion page we simply have to wrap it in a cfcache block. The next section of code is again entirely dynamic. The fourth and final section is wrapped in another set of cfcache tags. When you execute this code for the first time, the output will show the same date/time for all four sections of code, like this:

view plain print about
1I'm real-time dynamic data {ts '2009-11-16 10:49:50'}
2I'm cached dynamic data: {ts '2009-11-16 10:49:50'}
3I'm also real-time dynamic data {ts '2009-11-16 10:49:50'}
4I'm cached dynamic data too: {ts '2009-11-16 10:49:50'}

Running the code a few seconds later has different results:

view plain print about
1I'm real-time dynamic data {ts '2009-11-16 10:51:16'}
2I'm cached dynamic data: {ts '2009-11-16 10:49:50'}
3I'm also real-time dynamic data {ts '2009-11-16 10:51:16'}
4I'm cached dynamic data too: {ts '2009-11-16 10:49:50'}

In this case, the output contains both dynamic data (the first and third lines) as well as cached data (the second and fourth lines). Using the template cache it's easy to see how you can mix both dynamic data and multiple fragments of data that needs to be cached on the same page. There's really not a whole lot for you to do. You simply wrap the content you want to cache in a cfcache block and ColdFusion handles the rest. There are a few things you can control like cache timeouts, but we'll cover that in a full blog post dedicated to the template cache and all of it's features.

The object cache gives you much more granular control over what you cache than the template cache does. Using the object cache, you can pretty much cache anything you want – simple values, complex variables, objects, files, and just about anything else you want to throw at it. The advantage to using the object cache is that you have complete control over key names, get/put/remove operations, and cache expiry/eviction. This takes a little more work on your part but what you give up in convenience you easily gain back in flexibility and control. You can work with the object cache using both the cfcache tag as well as the new caching functions introduced in ColdFusion 9. Here's a very basic example of how you can cache the results of a query in an object cache using the cfcache tag:

view plain print about
1<cfcache
2    action="get"
3    id="artistQuery"
4    name="getArtists">

5
6<!--- go to the cache. If the data is not there,
7 go to the db then repopulate the cache --->

8<cfif isNull(getArtists)>
9
10    <!--- call getter then setter to retrieve new
11     value then update the cache --->

12    <cfquery name="getArtists" datasource="cfartgallery">
13        SELECT *
14        from artists
15    </cfquery>
16    
17    <cfcache
18        action="put"
19        id="artistQuery"
20        value="#getArtists#"
21        timespan="#createTimeSpan(0,0,1,0)#">

22</cfif>
23
24<h3>Query:</h3>
25<cfdump var="#getArtists#">

In this code, the first thing we do is try to pull our query out of the cache using the cfcache tag with action="get". The key that identifies our cached query in the object cache is set using id="artistQuery". Of course the first time we run this the query won't be in the cache, so the result variable we specified (name="getArtists") will return Null. After we attempt to pull the query from the cache, we then use the isNull function to see if anything was returned from our get operation. If getArtists is Null, we know that the query data isn't in the cache so we need to run our query, retrieve the data and then place it in the cache using the cfcache tag with action="put". When we do our cache put, we set id="artistQuery", which is the name of our cache key. The value to store in the cache is our ColdFusion query (value="getArtists") and we can specify how long the data should be cached using the timespan argument. The first time you execute the page (with debugging turned on), you'll notice that there's debugging information for your executed SQL Queries – because the query data didn't exist in the cache yet and you told ColdFusion to go off and get it from the database and put it into the cache. If you execute the page again, you won't see any debug info for your SQL Queries because ColdFusion is pulling the data from the cache and not from the database. It's important to note that in the dump of the query data from this example, Cached will always be False, regardless of whether you are accessing cached data or not. This is because Cached refers to whether or not the result set is in the ColdFusion Query Cache, which it is not because we are using Coldfusion's Ehcache implementation here and not the built in query cache. There's a lot more you can do with the object cache which we'll cover in another blog post.

If you're using ColdFusion 9's new Hibernate ORM functionality you can configure the ORM such that it uses Hibernate as its second level cache. This is a more complicated topic that we have time to discuss now, so let's table it for another blog post.

When you create a ColdFusion application and your application uses an Application.cfc or Application.cfm file, ColdFusion automatically creates a template cache and an object cache for you. These caches are bound to your application name (defined in your cfapplication tag for an Application.cfm file or this.name if you are using Application.cfc). If you have an unnamed application, ColdFusion will create a cache that is shared and accessible among all unnamed applications. It's important to remember that caches are not tied to ColdFusion scopes. If your application times out, this does not affect the cache(s) you create with Ehcache.

That's about it for getting to know the basics of Ehcache in ColdFusion 9. In Part 6 we'll start looking at the ehcache.xml file and how it can be used to configure the behavior of the caches you create in ColdFusion 9.