Tuesday, September 9, 2014

Ehcache Tutorial

Ehcache is caching framework in Java and is one of the most popular one. Ehcache is also used by Hibernate as second level cache mechanism. In this post, we will see how a basic Ehcache can be created and used in your application. 

Caches are essentially a key value map and helps in speeding up the application. For example, if you know that certain data does not changes in database and is frequently accessed, you might just want to load that data upfront in a cache in memory so that the access is faster and will avoid a database lookup. 

One thing you might want to be careful with usage of cache is the design of system should be such
that the cache should not contain stale objects otherwise they can introduce hard to find bugs. Think about caches right up front as part of your design. Usually a good idea is to put cache in the service layer. Any update to an object should result in following:
  • Invalidate the object in cache
  • Push the data to database.
  • If required reload the data or it might get reloaded in next fetch.
Let's see how we can make use of Ehcache. For Ehcache, first put the dependency in Maven pom.xml

<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
        <!--  Check the latest version in maven repository -->
<version>2.8.3</version>
</dependency>

For booting up ehcache, an ehcache,xml configuration file is specified. For this example, put the file in a classpath.

<?xml version="1.0" encoding="UTF-8"?>
     
<ehcache name="cacheManagerFromConfiguration">
      <defaultCache
          maxElementsInMemory="5"
          eternal="false"
          timeToIdleSeconds="60"
          timeToLiveSeconds="60"
          overflowToDisk="true"
          diskSpoolBufferSizeMB="15"
          maxElementsOnDisk="5"
          diskPersistent="false"
          diskExpiryThreadIntervalSeconds="60"
          memoryStoreEvictionPolicy="LRU"/>
     
       <!-- 
             Different memory policies
             Least Recently Used (LRU)
             Least Frequently Used (LFU)
             First In First Out (FIFO) 
          -->
      <cache name="studentsCache"
             maxElementsInMemory="2"
             maxElementsOnDisk="0"
             eternal="false"
             timeToIdleSeconds="60"
             timeToLiveSeconds="0"
             memoryStoreEvictionPolicy="FIFO">
      </cache>
     
</ehcache>

Let's use a simple POJO which will be inserted in cache

public class Student {
Long id;

String name;
    
 //Getters and Setters for id and name

Now let's write a main program to access the cache, insert some element and also create a cache programmatically

public class EhCacheMain {


public static void main(String[] args) {



// Read the cache details from ehcache.xml
String fileName = "ehcache.xml";
InputStream inputStream = EhCacheMain.class.getClassLoader()
.getResourceAsStream(fileName);
CacheManager cacheManager = CacheManager.create(inputStream);

// Print out all the cache defined
for (String cacheName : cacheManager.getCacheNames()) {
Cache cache = cacheManager.getCache(cacheName);
System.out.println("Cache is: " + cache.getName());
}

// Let's get hold of studentsCache
Cache studentsCache = cacheManager.getCache("studentsCache");

// Let's make four student object
Student student1 = new Student(1L, "Ishana");
Student student2 = new Student(2L, "Ekagra");
Student student3 = new Student(3L, "Dunnu");
Student student4 = new Student(4L, "Chukku");

// Insert two object in cache
studentsCache.put(new Element(student1.getId(), student1));
studentsCache.put(new Element(student2.getId(), student2));

// Check that the cache size is 2
System.out.println("Cache Size: " + studentsCache.getSize());

// Let's insert two more students
studentsCache.put(new Element(student3.getId(), student3));
studentsCache.put(new Element(student4.getId(), student4));

// The cache size still remains 2 as we have specified max
// 2 elements in the cache
System.out.println("Cache Size: " + studentsCache.getSize());

// As the policy is FIFO, the first two elements are evicted
// and last two objects remain in cache, You will see 
                //Chukku and Dunnu printed
for (Long key : (List<Long>) studentsCache.getKeys()) {
System.out.println("Student element: "
               ((Student) studentsCache.get(key).getObjectValue())
.getName());
}

// Creating a cache programmatically
//You can also create a cache object and in the constructor you
//can provide all the parameters to configure it.
cacheManager.addCache("anotherStudentsCache");

// Print out all the cache defined
for (String cacheName : cacheManager.getCacheNames()) {
Cache cache = cacheManager.getCache(cacheName);
System.out.println("Cache is: " + cache.getName());
}
//Shutdown the cache
cacheManager.shutdown();
}

}


Ehcache  also provides the ability to see statistics of various aspects of cache hit and cache miss. Cache hit is when the object is found in the cache and cache miss is when the object is not found in cache and underlying data storage is hit to fetch the object

No comments:

Post a Comment