近期项目用到Ehcache,以前项目主要用到Oscache,并且缓存也是针对orm来处理,只要配置就好,不需要自定义缓存,不需管理缓存。下面描述一下,Spring+Ehcache来处理缓存。
1,首先引入jar包就不说了环境也不说了,要引入ehcache.xml文件(ehcache配置文件)。
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <cacheManagerEventListenerFactory class="" properties=""/> <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <Cache name="InstantCache" maxElementsInMemory="100000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="300" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <Cache name="fixCache" maxElementsInMemory="100000" eternal="true" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="false" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> <Cache name="methodCache" maxElementsInMemory="100000" eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" /> </ehcache>
2,自定义Ehcache配置文件ehcache-cfg.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <!-- 引用ehCache的配置 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>/WEB-INF/ehcache.xml</value> </property> </bean> <!-- 配置即时缓存 Start--> <bean id="instantCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="cacheManager" /> </property> <property name="cacheName"> <value>instantCache</value> </property> </bean> <!-- 配置即时缓存 End--> <!-- 配置固定缓存 Start--> <bean id="fixCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="cacheManager" /> </property> <property name="cacheName"> <value>fixCache</value> </property> </bean> <bean id="fixCacheInterceptor" class="FixCacheInterceptor"></bean> <!--红色字为自定类--> <bean id="fixCacheAfterAdvice" class="FixCacheAfterAdvice"></bean> <!--红色字为自定类--> <bean id="fixCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="fixCacheInterceptor" /> </property> <property name="patterns"> <list><!-- 不能为空,不然SpringHelper会报拿不到bean的错 --> <value>.*findAllConfig.*</value> <value>.*getConfig.*</value> <value>.*queryConfig.*</value> <value>.*listConfig.*</value> <value>.*searchConfig.*</value> <value>.*loadConfig.*</value> </list> </property> </bean> <bean id="fixCachePointCutAdivsor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="fixCacheAfterAdvice" /> </property> <property name="patterns"> <list> <value>.*createConfig.*</value> <!--value>.*saveConfig.*</value--> <!--value>.*addConfig.*</value--> <!--value>.*updateConfig.*</value--> <!--value>.*delConfig.*</value> <value>.*deleteConfig.*</value> <value>.*modConfig.*</value--> <value>.*freeConfig.*</value> <value>.*bindConfig.*</value> </list> </property> </bean> <!-- 配置固定缓存 End--> <!-- 配置接口缓存 Start--> <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager"> <ref local="cacheManager" /> </property> <property name="cacheName"> <value>methodCache</value> </property> </bean> <!-- find/create cache拦截器 excludeMethods 过滤的方法--> <bean id="methodCacheInterceptor" class="MethodCacheInterceptor"> <property name="excludeMethods"> <value> deleteConfig,findConfig </value> </property> </bean> <!-- flush cache拦截器 excludeMethods 过滤的方法--> <bean id="methodCacheAfterAdvice" class="MethodCacheAfterAdvice"> <property name="excludeMethods"> <value> deleteConfig,findConfig </value> </property> </bean> <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="methodCacheInterceptor" /> </property> <property name="patterns"> <list> <value>.*find.*</value> <value>.*get.*</value> <value>.*query.*</value> <value>.*list.*</value> <value>.*search.*</value> <value>.*load.*</value> </list> </property> </bean> <bean id="methodCachePointCutAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <property name="advice"> <ref local="methodCacheAfterAdvice" /> </property> <property name="patterns"> <list> <value>.*create.*</value> <value>.*save.*</value> <value>.*add.*</value> <value>.*update.*</value> <value>.*del.*</value> <value>.*delete.*</value> <value>.*mod.*</value> <value>.*free.*</value> <value>.*bind.*</value> </list> </property> </bean> <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="proxyTargetClass"> <value>false</value> </property> <property name="beanNames"> <list> <value>*BO</value> </list> </property> <property name="interceptorNames"> <list> <value>fixCachePointCut</value> <value>fixCachePointCutAdivsor</value> <value>methodCachePointCut</value> <value>methodCachePointCutAdvice</value> </list> </property> </bean> <!-- 配置接口缓存 End --> <!-- 刷新固定缓存定时器 Start--> <bean id="FixJobDetail" class="org.springframework.scheduling.quartz.JobDetailBean"> <property name="jobClass"> <value>com.ot.opf.timer.FixCacheJob</value> </property> </bean> <bean id="FixCacheTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="FixJobDetail" /> <property name="cronExpression"> <value>0 0 2 * * ?</value> </property> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list><ref bean="FixCacheTrigger"/></list> </property> </bean> <!-- 刷新固定缓存定时器 End --> </beans>
3,增加相应缓存的管理类
(1)FixEhCacheManager
import java.util.List; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.apache.log4j.Logger; public class FixEhCacheManager { private static Cache fixCache = (Cache)SpringHelper.getBean("fixCache"); private static Logger logger = Logger.getLogger(FixEhCacheManager.class); private static boolean isStop = true;//初始化暂停 public synchronized static boolean isStop() { return isStop; } public synchronized static void setStop(boolean isStop) { FixEhCacheManager.isStop = isStop; } public synchronized static void put(Object key,Object value){ if(!isStop()){ Element e = new Element(key,value); logger.debug("cache object to fixCache... key:"+key+",size of value"+e.getSerializedSize()); fixCache.put(e); } } public synchronized static Object get(Object key){ if(isStop())return null; Element element = fixCache.get(key); if(element!=null)logger.debug("get object from fixCache... key:"+key); return element == null ? null : element.getObjectValue(); } public synchronized static void remove(Object key){ logger.debug("remove object from fixCache... key:"+key); fixCache.remove(key); } public synchronized static void removeAll(){ logger.debug("remove all object from fixCache"); fixCache.removeAll(); } public synchronized static List getKeys(){ return fixCache.getKeys(); } public synchronized static int getSize(){ return fixCache.getSize(); } public synchronized static String getCacheName(){ return fixCache.getName(); } public synchronized static String getCacheKey(Class _class, String methodName, Object... arguments) { StringBuffer sb = new StringBuffer("fixCache_"); sb.append(_class.getName()).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sb.append(".").append(arguments[i]); } } return sb.toString(); } }
(2)InstantEhCacheManager
import java.util.List; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.apache.log4j.Logger; public class InstantEhCacheManager { private static Cache instantCache = (Cache)SpringHelper.getBean("instantCache"); private static Logger logger = Logger.getLogger(InstantEhCacheManager.class); private static boolean isStop = true;//初始化停止 public synchronized static boolean isStop() { return isStop; } public synchronized static void setStop(boolean isStop) { InstantEhCacheManager.isStop = isStop; } public synchronized static void put(Object key,Object value){ if(!isStop()){ Element e = new Element(key,value); logger.debug("cache object to instantCache... key:"+key+",size of value��"+e.getSerializedSize()); instantCache.put(e); } } public synchronized static Object get(Object key){ if(isStop())return null; Element element = instantCache.get(key); if(element!=null)logger.debug("get object from instantCache... key:"+key); return element == null ? null : element.getObjectValue(); } public synchronized static void remove(Object key){ logger.debug("remove object from instantCache... key:"+key); instantCache.remove(key); } public synchronized static void removeAll(){ logger.debug("remove all object from instantCache"); instantCache.removeAll(); } public synchronized static List getKeys(){ return instantCache.getKeys(); } public synchronized static int getSize(){ return instantCache.getSize(); } public synchronized static String getCacheName(){ return instantCache.getName(); } public synchronized static String getCacheKey(Class _class, String methodName, Object... arguments) { StringBuffer sb = new StringBuffer("instantCache_"); sb.append(_class.getName()).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sb.append(".").append(arguments[i]); } } return sb.toString(); } }
(3)MethodEhCacheManager
import java.util.List; import net.sf.ehcache.Cache; import net.sf.ehcache.Element; import org.apache.log4j.Logger; public class MethodEhCacheManager { private static Cache methodCache = (Cache)SpringHelper.getBean("methodCache"); private static Logger logger = Logger.getLogger(MethodEhCacheManager.class); private static boolean isStop = true;//初始化暂停 public synchronized static boolean isStop() { return isStop; } public synchronized static void setStop(boolean isStop) { MethodEhCacheManager.isStop = isStop; } public synchronized static void put(Object key,Object value){ if(!isStop()){ Element e = new Element(key,value); logger.debug("cache object to methodCache ... key:"+key+",size of value��"+e.getSerializedSize()); methodCache.put(e); } } public synchronized static Object get(Object key){ if(isStop())return null; Element element = methodCache.get(key); if(element!=null)logger.debug("get object from methodCache... key:"+key); return element == null ? null : element.getObjectValue(); } public synchronized static void remove(Object key){ logger.debug("remove object from methodCache... key:"+key); methodCache.remove(key); } public synchronized static void removeAll(){ logger.debug("remove all object from methodCache"); methodCache.removeAll(); } public synchronized static List getKeys(){ return methodCache.getKeys(); } public synchronized static int getSize(){ return methodCache.getSize(); } public synchronized static String getCacheName(){ return methodCache.getName(); } public synchronized static String getCacheKey(Class _class, String methodName, Object... arguments) { StringBuffer sb = new StringBuffer("methodCache_"); sb.append(_class.getName()).append(".").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sb.append(".").append(arguments[i]); } } return sb.toString(); } }
4,aop相应的类,只要对上面的通过BeanName捕获到,执行相应的AOP处理相应的缓存放入和移出。