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 :
- Le Jar de EhCache, actuellement : ehcache-1.1.jar.
- Le jar de log4j, actuellement : log4j-1.2.9.jar.
- Jakarta Commons Collections : http://jakarta.apache.org/commons/collections/.
- Jakarta Commons Loggins : http://jakarta.apache.org/commons/logging/
2) Configurer le système de logs (pour mon exemple log4j) :
Fichier : WEB-INF/log4j.properties
1 2 3 4 5 6 7 8 9 |
# 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
/* * 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
<!-- 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 --> <!-- 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. --> <!--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" --> |
5) Création d’un servlet utilisant EhCache pour mémoriser un objet :
Fichier : TestServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
/* * 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!--?xml version="1.0" encoding="ISO-8859-1"?--> ehCacheSample Démonstration de l'utilisation du cache : EhCache par tellaw.org <!-- Declaration des servlets --> MovieServlet com.tellaw.ehCacheSample.servlets.TestServlet <!-- Declaration du mapping --> 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 :
- Le site de ehCache : ehcache
2 réponses sur « Gerer un cache avec EhCache. »
cool
Gerer un cache avec EhCache…
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 l…