Top

Gerer un cache avec EhCache.

(1 votes, 3 / 5)
Loading ... Loading ...

Posté le par admin

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

<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) 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<br/>");
 
		// Lecture du cache pour extraire l'objet
		try {
			element = cache.get("The Ring");
		} catch (Exception e) {}
 
		Movie mySecondMovie = (Movie)element.getValue();
 
		out.println("<br/><br/>Cache chargé dans l'objet mySecondMovie<br/>");
		out.println("Nom : " + mySecondMovie.getName() +"<br/>");
		out.println("Description : " + mySecondMovie.getDescription() +"<br/>");
		out.println("Acteur : " + mySecondMovie.getActor() +"<br/>");
	}
}

6) Le fichier web.xml mappant la 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>
		Démonstration de l'utilisation du cache : EhCache par 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 :

  • 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 :

Espace de communautaire - postez vos commentaires




Bottom