Java Cache Tutorial with Method Annotations (CDI)

From Resin 4.0 Wiki

Revision as of 00:00, 28 January 2012 by Ferg (Talk | contribs)
Jump to: navigation, search

Squirrel-48.pngCookbook-48.png

Java caching can speed application performance and lower database load by annotating cacheable methods. The Java caching API (JCache) includes standard method annotations that let you add caching just by annotating your methods. Assuming your bean is a Java Dependency Injection (CDI) bean, your method will be cached automatically. When using an application server like the Resin application server that supports both CDI and JCache, you can add caching easily without much configuration.

You'll want to cache to

  • Improve latency
  • Reduce database load
  • Reduce CPU use

With the caching annotations, you can add caching with the following two steps:

  1. Add a @CacheResult annotation to the method you want to cache
  2. Use Java Dependency Injection (CDI) to get the bean

In the example, we'll inject the MyBean into a servlet for testing using the CDI @Inject method.

Contents

Using @CacheResult with the action bean

MyBean.java

 package org.example.mypkg;

 public class MyBean {
   @CacheResult
   String doLongOperation(String key)
   {
     ...
   }
 }

Using CDI @Inject in a Servlet

MyServlet.java

 package org.example.mypkg;

 public class MyServlet extends GenericServlet {
   @Inject MyBean _bean;

   public void service(ServletRequest req, ServletResponse res)
     throws IOException, ServletException
   {
     PrintWriter out = res.getWriter();
 
     String result = _bean.doLongOperation("test");
  
     out.println("test: " + result);
   }
 }

Enabling CDI Scanning

WEB-INF/beans.xml

 <beans/>

Performance Benefits of Caching

Personal tools
TOOLBOX
LANGUAGES