Google

Oct 17, 2013

Ehcache a beginner level tutorial

Q. Why would you cache objects in your Java application?
A. Caching can boost performance by offloading your database, and simplifying scalability.

Q. Have you used any cahing framework in Java?
A. Yes. Ehcache is the most widely-used Java-based cache because it’s robust, proven, and full-featured. Ehcache scales from in-process, with one or more nodes, all the way to mixed in-process/out-of-process configurations with terabyte-sized caches. For applications needing a coherent distributed cache, Ehcache uses the open source Terracotta Sever Array. In Hibernate you can configure Ehcache as your second-level cache.

Here is a simple tutorial.

Step 1: Maven pom.xml file to show dependency.


<dependency>
 <groupId<net.sf.ehcache</groupId>
 <artifactId<ehcache-core</artifactId>
 <version<2.5.2</version>
</dependency>


Step 2: Define the ehcache config file ehcache.xml under src/main/resources/ehcache folder.

<?xml version="1.0" encoding="UTF-8"?>
    
<ehcache name="EmployeeCache">

      <defaultCache
          maxElementsInMemory="10000"
          eternal="false"
          timeToIdleSeconds="120"
          timeToLiveSeconds="120"
          overflowToDisk="true"
          diskSpoolBufferSizeMB="30"
          maxElementsOnDisk="10000000"
          diskPersistent="false"
          diskExpiryThreadIntervalSeconds="120"
          memoryStoreEvictionPolicy="LRU"/>
    
      <cache name="employees"
             maxElementsInMemory="100"
             maxElementsOnDisk="0"
             eternal="false"
             timeToIdleSeconds="120"
             timeToLiveSeconds="0"
             memoryStoreEvictionPolicy="LFU">
      </cache>
    
</ehcache>


Step 3: Define the model class Employee that needs to be Serializable.

package com.mycompany.app.ehcache;

import java.io.Serializable;

public class Employee implements Serializable
{
    private Integer emplId;
    private String firstName;
    private String lastname;
    
    public Employee(Integer emplId, String firstName, String lastname)
    {
        super();
        this.emplId = emplId;
        this.firstName = firstName;
        this.lastname = lastname;
    }
    
    public Integer getEmplId()
    {
        return emplId;
    }
    
    public void setEmplId(Integer emplId)
    {
        this.emplId = emplId;
    }
    
    public String getFirstName()
    {
        return firstName;
    }
    
    public void setFirstName(String firstName)
    {
        this.firstName = firstName;
    }
    
    public String getLastname()
    {
        return lastname;
    }
    
    public void setLastname(String lastname)
    {
        this.lastname = lastname;
    }
    
    @Override
    public String toString()
    {
        return "Employee [firstName=" + firstName + ", lastname=" + lastname + "]";
    }
    
}

Step 4: The next step is to define a SimpleEHCache class.

package com.mycompany.app.ehcache;

import java.io.InputStream;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

public class SimpleEHCache
{
    /**
     * The CacheManager provides us access to individual Cache instances
     */
    private static final CacheManager cacheManager;
    
    static
    {
        
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        InputStream resourceAsStream = contextClassLoader.getResourceAsStream("ehcache/ehcache.xml");
        cacheManager = CacheManager.create(resourceAsStream);
    }
    
    /**
     * A cache that we're designating to hold Employee instances
     */
    private Ehcache employeeCache;
    
    public SimpleEHCache()
    {
        // Load our employees cache:
        employeeCache = cacheManager.getEhcache("employees");
    }
    
    /**
     * Adds a new Employee to the Cache
     */
    public void addEmployee(Integer id, Employee employee)
    {
        // Create an EHCache Element to hold the Employee
        Element element = new Element(id, employee);
        
        // Add the element to the cache
        employeeCache.put(element);
    }
    
    /**
     * Retrieves a Employee from the cache
     */
    public Employee getEmployee(Integer id)
    {
        // Retrieve the element that contains the requested Employee
        Element element = employeeCache.get(id);
        if (element != null)
        {
            
            return (Employee) element.getValue();
        }
        
        return null;
    }
}


Step 5: Finally, the unit test class.

package com.mycompany.app.ehcache;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class SimpleEHCacheTest
{
    private SimpleEHCache simpleEHCacheExample;
    
    @Before
    public void setUp()
    {
        // Create a sample SimpleEHCacheExample object
        simpleEHCacheExample = new SimpleEHCache();
        
        // Add a few employees
        simpleEHCacheExample.addEmployee(1, new Employee(1, "John", "Sander"));
        simpleEHCacheExample.addEmployee(2, new Employee(2, "Peter", "Sander"));
        simpleEHCacheExample.addEmployee(3, new Employee(3, "Emma", "Sander"));
    }
    
    @Test
    public void testRetrieve()
    {
        Employee employee = simpleEHCacheExample.getEmployee(1);
        Assert.assertNotNull("The employee was not found in the cache", employee);
        Assert.assertEquals("Did not find the correct employee", "John", employee.getFirstName());
    }
    
    @Test
    public void testRetrieveNotFound()
    {
        Employee employee = simpleEHCacheExample.getEmployee(5);
        Assert.assertNull("I did not expect find the employee in the cache but it was there", employee);
    }   
}


Labels:

4 Comments:

Blogger Priyanka said...

excellent

thanks dear.....

7:14 PM, May 07, 2014  
Blogger Unknown said...

Thanks Priyanka. Your name sounds like a fellow Srilankan :)

2:13 PM, May 22, 2014  
Anonymous Anonymous said...

What happens if the cached data has been modified in the database?

2:07 PM, October 12, 2014  
Blogger Unknown said...

That is why you need to have a cache refresh strategy. For example, every 15 minutes, etc. Some data cannot be cached when the latest info is to be displayed.

10:25 AM, October 13, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

<< Home