Accessibility
Brian Szoszorek

Brian Szoszorek

BrianSzoszorek.com

Created:
24 July 2006
User Level:
Intermediate
Products:
Coldfusion

Clearing template cache automatically through the ColdFusion gateway

In Macromedia ColdFusion, turning on the Trusted Cache in the Administrator can help boost your applications' performance by reducing file overhead during requests.

With this option enabled, the ColdFusion application server will execute a template; for all subsequent requests to that template, ColdFusion executes the template stored in the server's RAM without ever checking the disk for an updated or changed template. In short, this is a less expensive process because ColdFusion does not check the file system for changes during every request.

If you make frequent changes to your ColdFusion templates, though, you must clear the template cache every time or your server will not reflect the changes to your template. To clear the template cache, you typically must log in to the Administrator and select the Clear Template Cache option. This article, however, shows you how to clear the template cache using the ColdFusion event gateway and the Admin API. You will be able to turn on Trusted Cache to take the file IO out of template requests and put it into a separate process that ColdFusion will use to check for changes and clear the template cache for you.

This solution uses several ColdFusion features. You will use Trusted Cache to reduce file overhead during file requests, an event gateway to monitor file changes, and the Admin API to clear the template cache.

Requirements

To complete this tutorial you will need to install the following software and files:

ColdFusion MX 7 Enterprise

Sample files:

Prerequisite knowledge

  • Basic understanding of ColdFusion
  • Basic knowledge of ColdFusion components (CFCs)

Setting up the event gateway

First you must create two files that the event gateway needs: a configuration file and a simple ColdFusion component:

  1. Log in to your ColdFusion Administrator, click Trusted Cache, and submit your changes (see Figure 1).

    The Trusted cache option in the ColdFusion Administrator

    Figure 1. Trusted Cache option in the ColdFusion Administrator

  2. Create a directory under your webroot called clearcache. If your webroot is c:\inetpub\wwwroot\, your directory would be defined as c:/inetpub/wwwroot/clearcache. This is the directory that your CFG and CFC file will monitor for any changes.
  3. Create a directory on your hard drive called c:\cacheClear. This is where you will place the configuration file and ColdFusion component.
  4. Open Notepad or any text editor and enter the following code:

    directory=c:/inetpub/wwwroot/clearcache
    recurse=yes
    extensions=cfm,cfc
    interval=1000
    

    Note: In the CFG file, when specifying the directory that you want to monitor, you must use forward slashes (/) instead of back slashes (\) due to the Java runtime in ColdFusion MX 7.

  5. Save the file as templateListener.cfg and place it in the c:\cacheClear folder.

You may wonder what you just set up. Here is a brief explanation:

  • directory=c:/inetpub/wwwroot/clearcache: This attribute specifies the directory that monitors for file changes. You may change this location to match the directory you want to monitor.
  • recurse=yes: This attribute monitors subdirectories.
  • extensions=cfm,cfc: This attribute is a comma-delimited list of file extensions to monitor.
  • interval=10000: This attribute specifies how often to check for changes, in milliseconds.

Note: If you have your directory watcher checking a large directory of files for changes too often, this may cause extra overhead and performance strain on your server. Change the interval setting in your templateListener.cfg to one minute instead of every five seconds, for example. Always test these scenarios in a development environment first and adjust the settings and attributes for what works best for your setup before deploying to a production environment.

Creating the ColdFusion component

Now create the ColdFusion component to handle the file changes. Your component contains three functions: onAdd, onDelete, and onChange. As you can imagine, if a file is added, the event gateway will invoke the onAdd function; likewise, if a file is deleted, the event gateway will invoke the onDelete function, or if a file is changed, the event gatway will invoke the onChange function. When the event gateway invokes any of these functions, it will pass an argument called CFevent that contains the following structure with information about what happened:

  • TYPE: What happened? Values are one of the following: ADD, CHANGE, or DELETE.
  • FILENAME: Name of the file that was added, deleted, or changed.
  • LASTMODIFIED: Date and time the file was created or modified. (This field is not present if the file was deleted.)

Place this CFC in your cacheClear folder and name it templateListener.cfc. The component contains the following code, which shows the entire code for templateListener.cfc (which handles these events and clears the template cache):

<cfcomponent>
    <cffunction access="private" name="clearCache" returntype="void" output="false">
       <!--- log into your coldfusion admin --->
       <cfinvoke component="cfide.adminapi.administrator" method="login">
         <cfinvokeargument name="adminPassword" value="yourAdminPassword">
       </cfinvoke>
       <!--- clear template cache --->
       <cfinvoke component="cfide.adminapi.runtime" method="clearTrustedCache">
       <!--- log this action --->
       <cflog file="TemplateCacheEvents" application="No" text="Cache Cleared #now()#">
    </cffunction>
    <cffunction access="public" name="onAdd" output="no">
       <cfargument name="CFEvent" type="struct" required="yes"><cfset data=CFEvent.data>
         <!--- log this action --->
       <cflog file="TemplateCacheEvents" application="No" text="ACTION: #data.type#; FILE: #data.filename#; TIME: #timeFormat(data.lastmodified)#">
    </cffunction>
    <cffunction access="public" name="onDelete" output="no">
         <cfargument name="CFEvent" type="struct" required="yes">
            <!--- call our clearCache function --->
          <cfinvoke method="clearCache">
        <cfset data=CFEvent.data>
         <!--- log this action --->
          <cflog file="TemplateCacheEvents" application="No" text=" ACTION: #data.type#; FILE: #data.filename#">
    </cffunction>
    <cffunction access="public" name="onChange" output="no">
       <cfargument name="CFEvent" type="struct" required="yes">
          <!--- call our clearCache function --->
         <cfinvoke method="clearCache">
        <cfset data=CFEvent.data>    
       <!--- log this action --->
       <cflog file="TemplateCacheEvents" application="No" text=" ACTION: #data.type#;  FILE: #data.filename#;    TIME: #timeFormat(data.lastmodified)#">
    </cffunction>
</cfcomponent>

Now I'll break down these functions and explain what they do.

The clearCache function

The event gateway invokes this function when you delete or change a file (Figure 2).

The clearCache function

Figure 2. The clearCache function

Lines 5–7: This code logs you in to the ColdFusion Administrator so you can invoke the clearTrustedCache method.

Line 9: Now that you are logged in to the Administrator, you invoke the method clearTrustedCache, which clears the Trusted Cache on the server, as you would expect.

Important: Change the value of adminPassword (line 6) to the password that works for your ColdFusion Administrator.

Line 11: This logic logs the information, so that you have a record of the event. It isn't required but I prefer to have a record of what happened on the server; it's also a way, while testing, to know that the solution is working.

Note: Best practices dictate that any methods that don't specifically need to be called from other ColdFusion templates should be private. Therefore, in this example I have set the clearCache method's access attribute to private.

The onAdd function

The event gateway invokes this function when the file is added (see Figure 3).

The onAdd function

Figure 3. The onAdd function

Line 19: You don't need to clear the cache when a file is added. However, because I love my logs, I want to record that a file was added to the server.

The onDelete function

The event gateway invokes this function when a file is deleted (see Figure 4).

The onDelete function

Figure 4. The onDelete function

Line 27: Now that a file has been deleted, you should clear the template cache. You will invoke the previously defined method, clearCache.

The onChange function

The event gateway invokes this function when a file has changed (see Figure 5).

The onChange function

Figure 5. The onChange function

Line 37: Now that a file has been modified, you should clear the template cache. Invoke the previously defined method, clearCache.

Testing the caching solution

Now that you have set up your event gateway configuration file and the CFC to handle events from the gateway, it's time to turn it on!

  1. Log in to your ColdFusion administrator and go to Event Gateways > Gateway Instances (see Figure 6).
  2. Give your instance an ID: Template Cache Manager. Select the DirectoryWatcher option for Gateway type. Type or browse to the path for your CFC and CFG files, and for the Startup Mode, select the Manual option. Click the Add Gateway Instance button.
Adding the event gateway instance and specifying its properties

Figure 6. Adding the event gateway instance and specifying its properties

  1. See your instance listed (see Figure 7).
See your DirectoryWatcher gateway.

Figure 7. See your DirectoryWatcher gateway

  1. Click the Start Button button to start your DirectoryWatcher event gateway instance.
  2. See that the Template Cache Manager event gateway instance is running (see Figure 8).
See your Directory Watcher instance running

Figure 8. See your DirectoryWatcher instance running

  1. Change some files in the c:\inetpub\wwwroot\clearcache directory or whichever directory you specified for watching in the templateListener.cfg file.
  2. In the ColdFusion Administrator, go to Debugging and Logging > Log Files. You will see a log called TemplateCacheevents.log (created by the CFC). Click it to see each change that you made recorded in the log, and when the template cache was refreshed (Figure 9).
The cache log

Figure 9. The cache log

That's it! You have now automated the clearing of the template cache so that you never have to worry about forgetting to clear it yourself after updating a ColdFusion template.

Going forward

Let's say you have a very critical file about which you need to be informed immediately if it changes for any reason. You could create a function that checks whether the changed filename matches the critical filename you're monitoring. This function could send you an e-mail, an SMS message, instant message, and much more.

Instead of logging the changes to a single log file, you could log them into a database table. A scheduled task could then run every Monday morning and create a report with graphs and charts, showing the file-change activity on the server during the past week and then e-mailing a professional report to a specified address in either a PDF or Macromedia FlashPaper 2 document.

Where to go from here

As a ColdFusion developer, you have many exciting and powerful tools at your disposal. ColdFusion MX 7 is a rapid web application development platform that allows you to accomplish many tasks with minimal work, and which is built on the Java platform. Coupling this with Flex 2 allows you to deliver the power of your ColdFusion application in rich, engaging interfaces that are sure to impress. When you approach a problem, think about how you can take the many ColdFusion MX 7 features and combine them together to create truly amazing web applications.

About the author

Brian Szoszorek has been developing ColdFusion applications since 2000. He is a certified ColdFusion developer and the chief technologist of New Point Media. He has worked and provided consulting services to companies such as New Era Cap Company, XL Capital, Spire Systems, and Adobe Systems. Brian is a strong evangelist for how ColdFusion, Flex, Adobe AIR, and the Flash Platform as they provide higher productivity and richer experiences compared to competing technologies.