Skip to content

Cache J2EE

OSCache

  • Licence : Apache modifiée

  • Points remarquables :

    • Taglib utilisable dans les JSP (cache par fragments)
    • Permet de bloquer les accès jusqu’à la fin d’une maj
    • Servlet Filter pour le cache

Utilisation avec fail-over

	String myKey = "myKey";
	String myValue;
	int myRefreshPeriod = 1000;
	try {
	    // Get from the cache
	    myValue = (String) admin.getFromCache(myKey, myRefreshPeriod);
	} catch (NeedsRefreshException nre) {
	    try {
	        // Get the value (probably from the database)
	        myValue = "This is the content retrieved.";
	        // Store in the cache
	        admin.putInCache(myKey, myValue);
	    } catch (Exception ex) {
	        // We have the current content if we want fail-over.
	        myValue = (String) nre.getCacheContent();
	        // It is essential that cancelUpdate is called if the
	        // cached content is not rebuilt
	        admin.cancelUpdate(myKey);
	    }
	}

Utilisation sans fail-over

	String myKey = "myKey";
	String myValue;
	int myRefreshPeriod = 1000;
	try {
	    // Get from the cache
	    myValue = (String) admin.getFromCache(myKey, myRefreshPeriod);
	} catch (NeedsRefreshException nre) {
	    try {
	        // Get the value (probably from the database)
	        myValue = "This is the content retrieved.";
	        // Store in the cache
	        admin.putInCache(myKey, myValue);
	        updated = true;
	    } finally {
	        if (!updated) {
	            // It is essential that cancelUpdate is called if the
	            // cached content could not be rebuilt
	            admin.cancelUpdate(myKey);
	        }
	    }
	}

Références

EHCache

  • Licence : Apache 2.0

  • Dépendances : common-collection et common-logging

  • Points remarquables :

    • Plusieurs politiques d’expiration de cache : LRU, LFU, FIFO
    • Multiples CacheManager par JVM
    • Fonctionne avec Hibernate
    • 86 % de “code coverage” pour les tests unitaires
    • Fonction de “vérouillage” du cache par un thread et de mise en attente des autres

Configuration

<ehcache>

    <diskStore path="java.io.tmpdir"/>

    <defaultCache
        maxElementsInMemory="10000"
        eternal="false"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
        />

    <cache name="sampleCache1"
        maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false"
        timeToIdleSeconds="300"
        timeToLiveSeconds="600"
        />

</ehcache>

Exemple

	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 service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	       // Creation du writer de sortie.
	       PrintWriter out = response.getWriter();
	       // Creation d'un objet
	       Object myObject = new Object();
	       // Mise en cache de cet element
	       Element element = new Element("testID", myObject);
	       cache.put(element);
	       out.println ("Objet mis en cache`<br/>`");   
	       // Lecture du cache pour extraire l'objet
	       try {
	           element = cache.get("testID");
	       } catch (Exception e) {}
	       Object mySecondObject = element.getValue();
	}
	}

Références

SwarmCache

Licence : LGPL Dépendances : JavaGroups, commons-collections et commons-logging Points remarquables :

  • Spécialisation dans la gestion de cache “clusterisables”

  • Fonctionne avec Hibernate

Exemple de registre de cache

	public class PersonCache extends GenericEntity {
	
	        ObjectCache cache;
	        
	        public PersonEntity(CacheFactory cacheFactory) {
	                cache = cacheFactory.createCache("Person");
	                // * Other initialization here
	        }
	        
	        public Person get(long key) {
	                Long cacheKey = new Long(key);
	                Person person = (Person)cache.get(cachekey);
	                if (person == null) {
	                        // * Get the object from the database                   
	                        if (person != null) {
	                                // Put it in the cache
	                                cache.put(cacheKey, person);
	                        }
	                }
	                return person;
	        }
	        
	        public void insert(Person person) {
	                // * Do database insert
	                // Add new object to cache
	                Long cacheKey = new Long(person.getKey());
	                cache.put(cacheKey, person);
	        }
	        
	        public void update(Person person) {
	                // * Do database update
	                // Remove object from cache
	                // (This causes all caches in the group to be notified)
	                Long cacheKey = new Long(person.getKey());
	                cache.clear(cacheKey);
	                // Re-add the object to the cache
	                cache.put(cacheKey, person);
	        }
	        
	        public void delete(long key) {
	                // * Do database delete
	                // Remove object from cache
	                // (This causes all caches in the group to be notified)
	                Long cacheKey = new Long(key);
	                cache.clear(cacheKey);          
	        }
	        
	}

Références

JBoss Cache

  • Licence : LGPL

  • Points remarquables :

    • Permet de cacher une arborescence d’objets “TreeCache”
    • Fonctionne avec Hibernate

Utilisation du cache POJO

	ArrayList list = new ArrayList();
	list.add("first");
	cache.putObject("/list/test", list); // Put the list under the aop cache
	list.add("second"); // Won't work since AOP intercepts the dynamic proxy not the original POJO.
	ArrayList myList = (List)cache.getObject("/list/test"); // we are getting a dynamic proxy instead
	myList.add("second"); // it works now
	myList.add("third");
	myList.remove("third");

Références