Top

Manage a Cache System with EHCache

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

Posted the by admin

The implementation of an Application cache is always a task which needs to impact many peoples and ressources to be done. EHCache is a simple and fast solution to implement, easy to connect with any existing application.

here is a sale-pitch which in my mind, defines the best EHCache:

“Ehcache is a pure Java, in-process cache”, “Available under the Apache 1.1 license. Ehcache’s copyright and licensing has been reviewed and approved by the Apache Software Foundation, making ehcache suitable for use in Apache projects.”

1) Dependencies:

2) Configuring the logging service (In this tutorial log4j) :

Fichier : WEB-INF/log4j.properties

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
 
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
 
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Please, note that for moving the application to a production server, we have to change the alerting level to avoid logging debug and info messages.

3) Creation of a sample serialyzable object to cache :

Fichier : Movie.java

/*
 * Created on 22 avr. 2005
 *
 */
 package com.tellaw.ehCacheSample;
 
 import java.io.Serializable;
 
 /**
 * @author Eric
 *
 */
 public class Movie implements Serializable {
 
	private String name = "";
	private String description = "";
	private String actor = "";
 
	public Movie () {
		// Default constructor.	
	}
 
	public String getActor() {
		return actor;
	}
 
	public void setActor(String actor) {
		this.actor = actor;
	}
 
	public String getDescription() {
		return description;
	}
 
	public void setDescription(String description) {
		this.description = description;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
}

4) External file configuration dedicated to EHCache :

Fichier : WEB-INF/ehCache.xml

<ehcache>
	<!-- 
		Sets the path to the directory where cache .data files are created.
 
		If the path is a Java System Property it is replaced by
		its value in the running VM.
 
		The following properties are translated:
		user.home - User's home directory
		user.dir - User's current working directory
		java.io.tmpdir - Default temp file path 
	-->
 
	<diskStore path="java.io.tmpdir"/>
	<!--
 
		Default Cache configuration. 
 
		These will applied to caches programmatically created through the CacheManager.
 
		The following attributes are required:        
		maxInMemory                    - Sets the maximum number of objects that will be created in memo
		eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the element is never expired.
		overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit.
 
		The following attributes are optional:
		timeToIdleSeconds              - Sets the time to idle for an element before it expires.  i.e. The maximum amount of time between accesses before an element expires Is only used if the element is not eternal.
		Optional attribute. A value of 0 means that an Element can idle for infinity.
		The default value is 0.
		timeToLiveSeconds              - Sets the time to live for an element before it expires.
		i.e. The maximum time between creation time and when an element expires.
		Is only used if the element is not eternal.
		Optional attribute. A value of 0 means that and Element can live for infinity.
		The default value is 0.
 
		diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
 
		The default value is false.
		diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. 
 
		The default value
		is 120 seconds.
 
	-->
 
	<defaultCache
 
		maxElementsInMemory="10000"
		eternal="false"
		timeToIdleSeconds="120"
		timeToLiveSeconds="120"
		overflowToDisk="true"
		diskPersistent="false"
		diskExpiryThreadIntervalSeconds="120"
 
	/>    
 
	<!--Predefined caches.  
		Add your cache configuration settings here.
 
		If you do not have a configuration for your cache a WARNING will be issued when the
		CacheManager starts
 
		The following attributes are required:
		name                           - Sets the name of the cache. This is used to identify the cache.
		It must be unique.
 
		maxInMemory                    - Sets the maximum number of objects that will be created in memory
		eternal                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the
		element is never expired.
 
		overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache
		has reached the maxInMemory limit.
 
		The following attributes are optional:
		timeToIdleSeconds              - Sets the time to idle for an element before it expires.
		i.e. The maximum amount of time between accesses before an element expires
		Is only used if the element is not eternal.
		Optional attribute. A value of 0 means that an Element can idle for infinity.
 
		The default value is 0.
 
		timeToLiveSeconds              - Sets the time to live for an element before it expires.
		i.e. The maximum time between creation time and when an element expires.
		Is only used if the element is not eternal.
		Optional attribute. A value of 0 means that and Element can live for infinity.
		The default value is 0.
 
		diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.
		The default value is false.
 
		diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value
		is 120 seconds.
	-->
 
 
	<!-- 
		Sample cache named sampleCache1
 
		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="sampleCache1"
			maxElementsInMemory="10000"
			eternal="false"
			overflowToDisk="false"
			timeToIdleSeconds="300"
			timeToLiveSeconds="600"
	/>
 
</ehcache>

5) Creating a test servlet which will try to load Objects from EHCache :

Fichier : TestServlet.java

/*
 * Created on 22 avr. 2005
 *
 */
 package com.tellaw.ehCacheSample.servlets;
 
 import java.io.IOException;
 import java.io.PrintWriter;
 
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
 import net.sf.ehcache.*;
 
 import com.tellaw.ehCacheSample.*;
 
 /**
 * @author Eric
 *
 */
 
 public class TestServlet extends HttpServlet {
 
	private static Logger logger = Logger.getLogger(TestServlet.class.getName());
 
	private CacheManager manager = null;
	private Cache cache = null;
 
	public void init() throws ServletException {
 
		// Configuration de log4J.
		PropertyConfigurator.configure( getServletContext().getRealPath ("WEB-INF/log4j.properties") );
 
		// Creating the cache manager from configuration file
		try {
			manager = CacheManager.create(getServletContext().getRealPath ("WEB-INF/ehCache.xml"));
			cache = manager.getCache("sampleCache1");
		} catch (Exception e) {
			logger.error("Unable to load EHCACHE configuration file");
		}
 
	}
 
	public void destroy() {}
 
	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		doGet(arg0, arg1);
	}
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
		// Output Writer creation		
		PrintWriter out = response.getWriter();
 
		// Creation of a test Movie Object
		Movie myMovie = new Movie ();
		myMovie.setName("The Ring");
		myMovie.setDescription("Film fantastique");
		myMovie.setActor("Naomi Watts");
 
		// Caching this element
		// Attention ce que la classe Movie implémente java.io.Serializable
		Element element = new Element(myMovie.getName(), myMovie);
		cache.put(element);
 
		out.println ("Objet mis en cache<br/>");
 
		// Reading the cache
		try {
			element = cache.get("The Ring");
		} catch (Exception e) {}
 
		Movie mySecondMovie = (Movie)element.getValue();
 
		out.println("<br/><br/>Cache loaded into the object mySecondMovie<br/>");
		out.println("Name : " + mySecondMovie.getName() +"<br/>");
		out.println("Description : " + mySecondMovie.getDescription() +"<br/>");
		out.println("Actor : " + mySecondMovie.getActor() +"<br/>");
	}
}

6) Web.xml File used to map the servlet :

Fichier : WEB-INF/web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app 	xmlns="http://java.sun.com/xml/ns/j2ee"
			xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
			xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
			version="2.4">
	<display-name>ehCacheSample</display-name>
	<description>
		EHCache tutorial from tellaw.org
	</description>
 
	<!-- Declaration des servlets -->
	<servlet>
		<servlet-name>MovieServlet</servlet-name>
		<servlet-class>com.tellaw.ehCacheSample.servlets.TestServlet</servlet-class>
	</servlet>
 
	<!-- Declaration du mapping -->
	<servlet-mapping>
		<servlet-name>MovieServlet</servlet-name>
		<url-pattern>/MovieServlet</url-pattern>
	</servlet-mapping>
</web-app>

Notes :

  • The official documentation doesn’t ask to provide Jakarta Commons Collections as a dependency..
  • Please do not forget to change the logging level of the application when deploying on production platforms.

Sites utiles :

Community Area - You can add comments here




Bottom