EhCache - How to Configure EhCache - Java @ Desk

Friday, February 27, 2015

EhCache - How to Configure EhCache

EhCache Introduction - How to Configure EhCache

1. What is EhCache – EHCache is a Standard Java Based cache for boosting performance. EhCache is robust, proven and full featured cache mechanism. We can use Ehcache as a general-purpose cache or a second-level cache for Hibernate. It can be integrated with the Hibernate, Spring or any other Java based third party tool.
2. Why EhCache – EhCache is a widely used for Java Distributed Cache for a general purpose caching, Java EE and Application Servers. It features scalable, fast, lightweight, JMX enabled and Distributed caching etc.
3. How to Configure EhCache

Following are the steps to Configure the EhCache for general purpose Caching –

i. Add EhCache JAR to classpath
ii. Provide the configuration using ehcache.xml and place it to classpath
iii. Create a CacheManager
CacheManager cacheManager = new CacheManager();


iv. Reference a Cache
Ehcache sampleCache = cacheManager.getEhcache("SampleCache");


v. Use it
sampleCache.put(new Element("key", "value"));
sampleCache.get("key");


4. Let's Explore
Through the Sample cache code I will try to explain how to configure and use the EhCache.
In coming post we will see how to integrate EhCache with Hibernate, Spring and any database application.

5. Demo Application – Using the Demo Application we will -
Create an Instance of Cache using ehcache.xml and CacheManager
Put the List of employee objects inside the cache first time
Access the cache by generating the random key and check whether the object is inside the cache or not?

i. JAR needed to run the project
http://ehcache.org/downloads/destination?name=ehcache-2.9.0-distribution.tar.gz&bucket=tcdistributions&file=ehcache-2.9.0-distribution.tar.gz

ii. Configure EhCache.xml
<?xml version="1.0" encoding="UTF-8"?>

<ehcache name="DefaultSampleCache">
  <defaultCache
      maxElementsInMemory="10000"
      eternal="false"
      timeToIdleSeconds="120"
      timeToLiveSeconds="120"
      diskSpoolBufferSizeMB="30"
      maxElementsOnDisk="10000000"
      diskExpiryThreadIntervalSeconds="120">
      <persistence strategy="localTempSwap"/>
  </defaultCache>
  <!-- Sample cache named sampleCache
    This cache contains a maximum in memory of 10000 elements, and will expire
    an element if it is idle for more than 5 minutes and lives for more than
    10 minutes.
 
    If there are more than 10000 elements it will overflow to the
    disk cache, which in this configuration will go to wherever java.io.tmp is
    defined on your system. On a standard Linux system this will be /tmp" -->
    
  <cache name="sampleCache" 
  maxEntriesLocalHeap="10000"
  maxEntriesLocalDisk="1000" 
  eternal="false" 
  diskSpoolBufferSizeMB="20"
  timeToIdleSeconds="300" timeToLiveSeconds="600"
  memoryStoreEvictionPolicy="LFU" 
  transactionalMode="off">
  <persistence strategy="localTempSwap" />
 </cache>
</ehcache>


iii. Initializing Cache Configuration and get the Cache Object
public class InitCache {
 
 private CacheManager cacheManager;
 
 public InitCache(){
  cacheManager = CacheManager.getInstance();
 }
 
 public Cache getCache(){
  return cacheManager.getCache("sampleCache");
 }
}




iv. Create a Object to put into the Cache
public class Employee implements Serializable {

 int id;
 String name;
 
 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + "]";
 }

 public int getId() {
  return id;
 }
 
 public void setId(int id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public Employee(int id, String name) {
  super();
  this.id = id;
  this.name = name;
 }

 public void setName(String name) {
  this.name = name;
 }
}


v. To Generate the 100 Objects Of Employee and keep as a List
public class EmployeeGenerator {

 public static List<Employee> list  = new ArrayList<Employee>();
 
 public static List<Employee> getAllEmployee(){
  for(int i=0;i<100;i++){
   list.add(new Employee(i, i+"name"));
  }
  return list;
 }
 
}


vi. Sample EHCache - Store the objects inside the cache and get the objects from cache using the key.
public class SampleEhCacheDemo {
 
 public static void main(String[] args) {
  
  InitCache cacheconf = new InitCache();
  
  Cache cache = cacheconf.getCache();
  
  // Put the Initial Employees in the Cache.
  
  List<Employee> allEmployee = EmployeeGenerator.getAllEmployee();
  
  for (Employee employee : allEmployee) {
   cache.put(new Element(employee.getId(), employee));
  }
  
  // Search Employee the randomly generated key –
 
  Random randomgenerator = new Random(110);
  for (int i=0;i<10;i++) {
   System.out.println("======");
   int random = randomgenerator.nextInt(110);
   Element ele = cache.get(random);
   String output = (ele == null ? null : ele.getObjectValue().toString());
   System.out.println("OutPut is "+output);
   System.out.println("Is Key ="+random+" Present in Cache "+ cache.isKeyInCache(random));
   System.out.println("======");
  }
 }

}


Summary – we have seen the basic of EhCache, how to configure EhCache, Put the object inside the cache and get the object back from the cache. Next Post we will see how to configure EhCache with Hibernate.

Tag – Ehcache, Caching, In Memory Caching, Java Caching.

This post is written by
Soumitra Pathak - Linkedin, Facebook

He is a freelance writer, loves to explore latest features in Java technology.







No comments:

Post a Comment