Friday, May 29, 2009

A Simple Cache That Works

In our last post we saw how to make a custom multiple write-single read class. In this post we see how to use basic caching to help us process information selectively. Caching is a complex thing, ie if you go to finer details. However, we needed something simple that we can log the way we want to (and know for sure that it works). I started with some complicated AOP that caches method results to only find using a basic cache to be more efficient.

There are three basic steps to using cache in the spring environment:

1. Configure the ehcache.xml and put it in your resources folder
EHCache Config

2. Put the required spring configuration, injecting the cache in the required bean
Spring Cache Config

3. Use the cache in the bean as you deem fit:
The multiple write, single read bean that uses caching
A helper bean that stores data being passed around

And, of course, you would need the ehcache and spring cache dependencies if you are using maven:
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>1.5.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>spring-cache</groupId>
<artifactId>spring-cache</artifactId>
<version>2.4.1</version>
</dependency>

No comments: