How to reduce database load by caching

From Resin 3.0

Revision as of 23:38, 13 January 2009 by Ferg (Talk | contribs)
Jump to: navigation, search


If I want to reduce database load and improve performance, I can cache database values in Resin's distributed cache. As long as the content exists in the cache, my application can avoid going to the database entirely. Because Resin's distributed cache is integrated with the clustering, it will ensure updates will be available for all servers consistently.

For example, I might have a blog commenting system, and want to avoid checking the database every time for the same comment text. If I can store it with Resin, I can avoid the database entirely. My code checks the cache first for the comment (#259). If it's missing, I'll ask the database for the content.

Because my comment storing code also saves updates to the cache, I'll automatically see edits, even if the changes happen on a different server.

cache.jsp

 <%@ page import="com.caucho.cluster.*" %>
 <%! @javax.webbeans.Current Cache _cache; %>
 <%
        String comment = (String) _cache.get("comment:259");
       if (value == null) {
            comment = lookup_comment(259);
            _cache.put("comment:259", value);
       }

       out.println("comment: " + comment);
 %>

The com.caucho.cluster.Cache is just a HashMap, so I can get and put just using Map methods.

I've used WebBeans-style dependency injection here because I want to keep my code free of dependencies. Any configuration stuff belongs in the config file.

I'll configure the cache in my resin-web.xml. The cache type is a TriadCache, which stores the data in triplicate (assuming I have at least 3 servers.)

The cache needs a unique name to distinguish it from other caches.

WEB-INF/resin-web.xml

 <web-app xmlns="http://caucho.com/ns/resin"
                     xmlns:cluster="urn:java:com.caucho.cluster">

     <cluster:TriadCache name="my-cache"/>

 </web-app>
Personal tools