La gestion d’un cache applicatif est souvent une question demandant pas mal de ressources pour être résolue. EhCache est une solution simple et rapide à mettre en oeuvre, capable de s’interfacer facilement avec vos applications, et même le système de logs de votre application !

Comme à mon habtude, voici n extrait du site de ehcache définissant ce produit :

« 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) Les dépendances :

2) Configurer le système de logs (pour mon exemple 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

Notez que pour le passage en production de votre application, il faut remonter le niveau d’alerte de log4j, sinon le serveur va logguer les messages de débug.

3) Création d’un objet serializable à mettre dans le 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 () {
		// Constructeur par défaut de movie.
	}

	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) Configuration de EhCache par un fichier de conf externe :

Fichier : WEB-INF/ehCache.xml

	

	

	

	

 

5) Création d’un servlet utilisant EhCache pour mémoriser un objet :

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 {

		// Creation du writer de sortie.
		PrintWriter out = response.getWriter();

		// Creation d'un objet Movie pour tester notre cache
		Movie myMovie = new Movie ();
		myMovie.setName("The Ring");
		myMovie.setDescription("Film fantastique");
		myMovie.setActor("Naomi Watts");

		// Mise en cache de cet 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
");

		// Lecture du cache pour extraire l'objet
		try {
			element = cache.get("The Ring");
		} catch (Exception e) {}

		Movie mySecondMovie = (Movie)element.getValue();

		out.println("

Cache chargé dans l'objet mySecondMovie
");
		out.println("Nom : " + mySecondMovie.getName() +"
");
		out.println("Description : " + mySecondMovie.getDescription() +"
");
		out.println("Acteur : " + mySecondMovie.getActor() +"
");
	}
}

 

6) Le fichier web.xml mappant la servlet :

Fichier : WEB-INF/web.xml



	ehCacheSample

		Démonstration de l'utilisation du cache : EhCache par tellaw.org

	

		MovieServlet
		com.tellaw.ehCacheSample.servlets.TestServlet

	

		MovieServlet
		/MovieServlet

 

Notes :

  • La documentation officielle ne donne pas comme dépendance Jakarta Commons Collections. En ce qui me concerne, j’ai une exception type ClassNotFound sur LRUMap.
  • Notez que pour le passage en production de votre application, il faut remonter le niveau d’alerte de log4j, sinon le serveur va loguer les messages de debug.

Sites utiles :