2010-06-02 14 views
13

que tiene esta configuración para Ehcache:Ehcache caché por defecto en Java

<ehcache> 
    <defaultCache 
      name="defaut" 
      maxElementsInMemory="5" 
      eternal="false" 
      timeToIdleSeconds="20" 
      timeToLiveSeconds="20" 
      overflowToDisk="false" 
      diskPersistent="false" 
      memoryStoreEvictionPolicy="LRU" 
      />   
</ehcache> 

¿Cómo puedo obtener acceso a la caché por defecto de Ehcache?

CacheManager.getInstance().getCache("default"); // returns null 
+0

"Estos ajustes se aplicarán a las cachés creado programáticamente "- _ehcache-failsafe.xml_. Y el elemento ** defaultCache ** no tiene el atributo ** name ** - _ehcache.xsd_. Por cierto 'CacheManager.getInstance(). AddCache (" default ")' throws "El caché predeterminado ya ha sido configurado". – cubanacan

Respuesta

20

Mi entendimiento es que el "caché por defecto" es en realidad una plantilla para la nueva caja que se crean, en lugar de ser un caché con nombre específico.

CacheManager.getCache solo devolverá una instancia de caché si ya se ha creado, por lo que tendrá que indicarle que cree una nueva, usando algo como addCacheIfAbsent(). El nombre no importa, se creará a demanda utilizando la configuración de caché predeterminada.

2

Me encontré con el mismo problema al intentar crear una nueva memoria caché.

Usando EhCache 2.7.3 No pude usar el método addCacheIfAbsent (..) ya que devuelve la clase EhCache en desuso, y no la clase Cache.

Mi primer intento fue el siguiente:

private Cache addCache(Class<?> cacheClazz) { 
    CacheConfiguration cacheConfiguration = null; 
    { 
     Cache defaultCache = getCacheManager().getCache("default"); 
     cacheConfiguration = defaultCache.getCacheConfiguration(); 
    } 
    Cache newCache = new Cache(cacheConfiguration); 
    getCacheManager().addCache(newCache); 
    return newCache; 
} 

Pero el uso de CacheManager.getCache ("default") devuelve NULL - así que sí, que no se parece como uno puede obtener una referencia al valor por defecto (plantilla) caché.

Me dieron el código de trabajo como sigue:

private Cache addCache(Class<?> cacheClazz) { 
    // get the default (template) cache configuration 
    CacheConfiguration cacheConfiguration = getCacheManager().getConfiguration().getDefaultCacheConfiguration(); 
    // give it a unique name or the process will fail 
    cacheConfiguration.setName(cacheClazz.getName()); 
    Cache newCache = new Cache(cacheConfiguration); 
    getCacheManager().addCache(newCache); 
    return newCache; 
} 

No era THREADSAFE (probado mediante pruebas simultáneas TestNG). La implementación final se ve de la siguiente manera:

private final static Map<String, String> firstRunMap = new ConcurrentHashMap<>(); 
private Cache addCache(Class<?> cacheClazz) { 
    final String mapKey = getMapKey(cacheClazz); 

    if (firstRunMap.get(mapKey) == null) { 
     synchronized(mapKey) { 
      if (firstRunMap.get(mapKey) == null) { 

       // ----------------------------------------------------- 
       // First run for this cache!!! 
       // ----------------------------------------------------- 

       // get the default (template) cache configuration 
       CacheConfiguration cacheConfiguration = getCacheManager().getConfiguration().getDefaultCacheConfiguration(); 
       // give it a unique name or the process will fail 
       cacheConfiguration.setName(cacheClazz.getName()); 
       Cache newCache = new Cache(cacheConfiguration); 
       getCacheManager().addCache(newCache); 

       // ----------------------------------------------------- 
       // First run complete!!! 
       // ----------------------------------------------------- 

       firstRunMap.put(mapKey, ""); 

       return newCache; 
      } 
     } 
    } 

    // Not the first thread 
    return getCache(cacheClazz); 
} 

    // This class is AbstractEhCache - change it to your class 
private String getMapKey(Class<?> cacheClazz) { 
    String mapKey = AbstractEhCache.class.getName() // to differentiate from similar keys in other classes 
      + "-" + cacheClazz.getName(); 
    // Using intern() on the key as I want to synchronize on it. 
    // (Strings with different hashCodes represent different locks) 
    return mapKey.intern(); 
} 

private Cache getCache(Class<?> cacheClazz) { 
    return getCacheManager().getCache(cacheClazz.getName()); 
} 
0

por favor refiérase a la API de ehcache

addCache

public void addCache (String cacheName)

  throws IllegalStateException, 
       ObjectExistsException, 
       CacheException 

Agrega una Ehcache basado en la caché predeterminada con el nombre de pila.

de: http://ehcache.org/apidocs/2.7.6/

esperanza para ayudarle!

0

Pero si añadimos una región llamada 'por defecto', ehcache arrojará una excepción:

net.sf.ehcache.ObjectExistsException: El caché por defecto ya se ha configurado