Two Servlet Filters Every Web Application Should Have
Subject:   Caching on DB intensive, No good.
Date:   2004-01-26 08:40:19
From:   jfalkner
Response to: Caching on DB intensive, No good.

You are right, when dealing with a database you need to be smarter about using a cache filter. The filter in this article will only cache a complete response (i.e. after DB info has been formatted to say HTML). However, this doesn't mean the cache isn't helpful for DB-based applications.

You can definitely cache slowly changing resources such as a generic news page or a collection of links for a short amount of time. Assume you have a page a links that is generated from a table you keep in a database. Assume you rarely add links, say once a day at most. What is the harm in caching the page for an hour or two, even a day, or several days? The greater point being, if you change the timing for how long something is cached, you can creatively use the given cache filter for many different things.

When you are dealing with user-specific pages, you need to be a little more creative. The cache needs to be able to distinguish when it can reuse its cache. For the given filter, this is as easy as encoding user-specific info in the URL. For example, assume user Joe has a links page that is similar to the above example but specific to his favorite links. You can still cache this info as long as the URL reflects that the content is Joe's links (e.g. showlinks.jsp?user=Joe) instead of everyone's links (e.g. showlinks.jsp). Likewise, this scheme will work for any user of your system assuming the URL reflects the change, and as with the eariler example there is usually several times you can take advantage of this caching technique, especially if you alter cache timeouts.

Hopefully that helps. Yes, you can cache DB info, you just need to understand how the cache identifies cached content, and keep in mind with this filter you have the source-code. Feel free to modify how it caches content so that you can make it work best with your web application.