Build a Better ColdFusion Cache Tag

Build a Better ColdFusion Cache Tag

aching is an essential strategy for improving the performance of your applications, and ColdFusion offers much pre-packaged functionality to assist in this area, including a number of application server caching settings in the ColdFusion Administrator. ColdFusion also offers caching options directly through ColdFusion tags. For example, developers can use the tag’s cachedAfter and cachedWithin settings to cache the results of database queries and the tag for its direct support of user-interface caching.

The tag is not without its limitations, however. It works very well when you want to cache a whole HTML page, but if you want to cache just part of a page, you are out of luck. The “page” is the smallest unit that can process. Such a restriction might be reasonable for simple applications, but almost any sophisticated application design uses some kind of templating system to assemble complex interfaces from a variety of individual ColdFusion scripts. As such, most modern application designs don’t allow whole pages to be cached since to do so requires a single script to serve as the root point for the whole application.

Many ColdFusion frameworks, like the popular Fusebox or the newer Mach-II, require that all traffic go through the same ColdFusion script (usually named something like index.cfm). If you place a tag on this page, only the first page accessed ever gets displayed.

Luckily, it’s quite easy to write a cache tag that can work with sections of pages, and this article describes a script that does just that. The tag is named CacheOMatic (click here to download it), so the first step is to create a file called CacheOMatic.cfm and save it to a directory where ColdFusion custom tags are stored (the paths indicated under the setting “Custom Tag Paths” in the ColdFusion Administrator, generally a default path that looks something like C:CFusionMXCustomTags).

When you want to cache a section of a page, you surround it with the tag , as in:

Here's some stuff to cache!

While you want to support a plain vanilla version of the tag, you also will add some optional parameters. The CacheOMatic tag will take the three inputs shown in Table 1, all optional.

Name The “Key” of the Cache
scope The scope in which you want to store this data; corresponds with ColdFusion scopes: application, session, and server
exp How long until the cache expires
Table 1. Optional Inputs for CacheOMatic

Verify Values
Your first step is to check for each of the inputs in Table 1 and supply some default values for the ones that are missing. To do this, use the tag:

If the name is missing, compose the tag name from the script name and the query string. For the expiration, use the same syntax used in ColdFusion datetime functions (which means that ‘m’ means “months” not “minutes”?’n’ indicates minutes, so be careful). By default, the expiration is set to “1,h”, which translates to one hour.

The next attribute tells ColdFusion where to cache the data:

By default, the cache is for the whole application, though you can also make the cache unique to a server (“server”) or even to an individual client (“session”). Setting the scope to “session” should be done with caution, however, as storing lots of data in the session scope can consume lots of memory. Do it only when it is safe and the tradeoffs are clear.

To simplify the code, create a pointer to the given scope and parse out the expiration information:

As for the actual data, store it in a ColdFusion struct, with the various items in the cache keyed to the “key” parameter above, and store the expiration data in a second struct. First, check whether these structs exist, and create them if not:

		

Now you do the actual caching work. The code is actually quite short. The outer if/then structure, which can be a bit confusing, looks like this:

		

Custom Tags execute twice: once for the starting tag and once for the ending tag. This structure executes the top set of statements when the first tag is read (), then executes the final statements when reading the end tag (). So at the end of each tag execution, you save the “stuff” inside the tag to the data struct and save an expiration for it to the expiration date struct.

Now the code inside the first tag is where you actually check to see if you should use cached data or not:

													#ptr.CacheOMatic[Attributes.key]#						

This algorithm is fairly straightforward, and it goes like this:

	If you have data in the cache for the key
Get the expiration date for the data
If the expiration date is greater than the current date
Output the data in the cache and exit this tag

Note that if you exit the tag by calling , the code inside the CacheOMatic tag will never run. This is the work you save if the cached data is not stale. If the data is stale, you allow the whole tag to execute.

To test the tag, create a minimal ColdFusion script as follows:
#Now()#
#Now()#

When you hit this page with your browser, you should see a page with two dates. If you keep refreshing, the first date will update after 20 seconds (hence, the expiration “20,s”), while the second date updates after one minute (“1,n”). Your cache tag is complete.

A Simple Performance Boost
Not all scripts can be cached, of course. For expensive database transaction code or other time-consuming ColdFusion code that does not need to be executed with every request, however, you now have an elegant and simple solution. Not bad for about 30 lines of code.

devx-admin

devx-admin

Share the Post:
5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

Copilot Revolution

Microsoft Copilot: A Suit of AI Features

Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

AI Girlfriend Craze

AI Girlfriend Craze Threatens Relationships

The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

AIOps Innovations

Senser is Changing AIOps

Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

Bebop Charging Stations

Check Out The New Bebob Battery Charging Stations

Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

Malyasian Networks

Malaysia’s Dual 5G Network Growth

On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

Advanced Drones Race

Pentagon’s Bold Race for Advanced Drones

The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

Important Updates

You Need to See the New Microsoft Updates

Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

Price Wars

Inside Hyundai and Kia’s Price Wars

South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

Solar Frenzy Surprises

Solar Subsidy in Germany Causes Frenzy

In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

Electric Spare

Electric Cars Ditch Spare Tires for Efficiency

Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

Solar Geoengineering Impacts

Unraveling Solar Geoengineering’s Hidden Impacts

As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

Razer Discount

Unbelievable Razer Blade 17 Discount

On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

Innovation Ignition

New Fintech Innovation Ignites Change

The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

Import Easing

Easing Import Rules for Big Tech

India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time