Wednesday, September 28, 2005

Caching web pages

Majorly two categories:

1. Caching the entire response
2. Caching a part of response

Caching the response

Basically this kind of caching is used for news sites, stock tickers, etc. In this approach, the entire web response is cached for a specific configured period of time. After the expiry time, whenever the request is made, the page is refreshed, cached and served back to the client. This is applicable for static and as well as dynamic pages. It is acheived thru Servlet Filters.

Let us assume, we have a JSP "DisplayInventory.jsp", which displays the inventory details read from the database. And the inventory details have the nature of changing in half-an-hour. In this scenario, we can cache the response from the DisplayInventory.jsp for half-an-hour. The response will be cached during the first hit to this page and will be served from this cache for the further requests. When the request is made for this page after half-an-hour, the page is executed once again and the modified data is read and displayed.

This is quite easy to implement it thru Servlet Filters. Anyhow, most of the application servers have these kind of Filters. My following example shows how to configure this setting for Weblogic Server.

web.xml:
   <filter>

<filter-name>InventoryCache</filter-name>

<filter-class>weblogic.cache.filter.CacheFilter

</filter-class>

<init-param>

<param-name>timeout</param-name>

<param-value>30</param-value>

<!-- Cache expiry setting -->

</init-param>

<init-param>

<param-name>verbose</param-name>

<param-value>true</param-value>

</init-param>

</filter>



<!-- Maps the jsp with the filter -->

<filter-mapping>

<filter-name>InventoryCache</filter-name>

<url-pattern>DisplayInventory.jsp</url-pattern>

</filter-mapping>

Caching a part of response

Let us say, only in couple of places in your JSP, you read data from database or do some calculation to produce the response. You can cache only these parts instead of the entire response. This is normally done using tag library tags. Mark the area in your JSP with the cache tags and specifying the timeout period. It is taken care. Writing caching tag library is easy too. Nevertheless, most application server vendors ship a variety of caching tag library tags.

Following example is for Weblogic Server

Let us assume, this is how the DisplayInventory.jsp is written
Header

.....



Body

.....

Some formatting



<wl:cache name="invCache" timeout="30">



Now, there are some tag lib tags

which is used to read data from database



</wl:cache>



End formatting



End Body

And in some part of the JSP, if you want to clear the cache.
<wl:cache name="invCache" flush="true"/>

There are some more parameters available in both the cases, to fine tune the cache.

No comments: