Thursday, February 07, 2013

Method cache using ehcache, Spring, Java

Configuration in application context
<ehcache:annotation-driven cache-manager="cacheManager"/> 

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
 <property name="configLocation"> <value>classpath:/ehcache-emrb-config.xml</value> </property> 
</bean> 

<bean id="managementService" class="net.sf.ehcache.management.ManagementService" init-method="init" destroy-method="dispose"> 
   <constructor-arg ref="cacheManager"/> 
   <constructor-arg ref="mbeanServer"/> 
   <constructor-arg index="2" value="true"/> 
   <constructor-arg index="3" value="true"/> 
   <constructor-arg index="4" value="true"/> 
   <constructor-arg index="5" value="true"/> 
 </bean> 
<bean id="mbeanServer" class="org.springframework.jmx.support.MBeanServerFactoryBean"> <property name="locateExistingServerIfPossible" value="true"/> </bean>

Configuration in ehcache config file
<?xml version="1.0" encoding="UTF-8"?> 
<ehcache> 
  <defaultCache maxElementsInMemory="500" eternal="true" overflowToDisk="false"
    memoryStoreEvictionPolicy="LFU" /> <cache name="siteValidationCache" eternal="true"
    maxElementsInMemory="25000" overflowToDisk="false" diskPersistent="false"       memoryStoreEvictionPolicy="LRU" /> 
</ehcache>


Code annotation to add
@Cacheable(cacheName = "xyzCache", keyGenerator = @KeyGenerator(name = "com.abc.def.ghi.common.data.impl.AbcCacheKeyGenerator"))
public SomePojo addSomeThingToCacheMethod(String some) throws DataAccessException {
}

Code annotation to remove
@TriggersRemove(cacheName="xyzCache",  keyGenerator = @KeyGenerator (
           name = "com.abc.def.ghi.common.data.impl.AbcCacheKeyGenerator"))))
public SomePojo deleteSomeThingFromCacheMethod(String some);

Programmatic way to access cache
Cache xyzCache = CacheManager.getInstance().getCache("xyzCache");
xyzCache.remove(someKey);

No comments: