EHcache实例演示

来源:互联网 发布:.net程序员项目经验 编辑:程序博客网 时间:2024/05/17 23:29

ehcache的配置文件:

<ehcache><diskStore path="java.io.tmpdir" /><defaultCache maxElementsInMemory="1000" eternal="false"timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" /><cache name="DEFAULT_CACHE" maxElementsInMemory="10000"eternal="false" timeToIdleSeconds="300000" timeToLiveSeconds="600000"overflowToDisk="true" /></ehcache>


ehcacheContext.xml配置:

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"><bean id="defaultCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">    <property name="configLocation">    <value>classpath:ehcache.xml</value>    </property> </bean> <!-- 定义ehCache的工厂,并设置所使用的Cache name --> <bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">    <property name="cacheManager">    <ref local="defaultCacheManager"/>    </property>    <property name="cacheName">       <value>DEFAULT_CACHE</value>    </property> </bean> <!-- find/create cache拦截器 --> <bean id="methodCacheInterceptor" class="com.co.cache.ehcache.MethodCacheInterceptor">    <property name="cache">    <ref local="ehCache" />    </property> </bean> <!-- flush cache拦截器 --> <bean id="methodCacheAfterAdvice" class="com.co.cache.ehcache.MethodCacheAfterAdvice">    <property name="cache">    <ref local="ehCache" />    </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>    </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>.*update.*</value>       <value>.*delete.*</value>    </list>    </property> </bean> </beans>

 

Java代码程序:

public class MethodCacheAfterAdvice implements AfterReturningAdvice, InitializingBean{private static final Log logger = LogFactory.getLog(MethodCacheAfterAdvice.class);private Cache cache;public void setCache(Cache cache){this.cache = cache;}public MethodCacheAfterAdvice(){super();}//拦截器对象、方法、参数、对象public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable{String className = arg3.getClass().getName();List list = cache.getKeys();for (int i = 0; i < list.size(); i++){String cacheKey = String.valueOf(list.get(i));if (cacheKey.startsWith(className)){cache.remove(cacheKey);logger.debug("remove cache " + cacheKey);}}}public void afterPropertiesSet() throws Exception{Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");}}


 

package com.co.cache.ehcache;import java.io.Serializable;import net.sf.ehcache.Cache;import net.sf.ehcache.Element;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.springframework.beans.factory.InitializingBean;import org.springframework.util.Assert;public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean{private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);private Cache cache;public void setCache(Cache cache){this.cache = cache;}public MethodCacheInterceptor(){super();}/** * 拦截Service/DAO的方法,并查找该结果是否存在,如果存在就返回cache中的值, 否则,返回数据库查询结果,并将查询结果放入cache */public Object invoke(MethodInvocation invocation) throws Throwable{String targetName = invocation.getThis().getClass().getName();String methodName = invocation.getMethod().getName();Object[] arguments = invocation.getArguments();Object result;logger.debug("Find object from cache is " + cache.getName());String cacheKey = getCacheKey(targetName, methodName, arguments);Element element = cache.get(cacheKey);if (element == null){logger.debug("Hold up method , Get method result and create cache........!");result = invocation.proceed();element = new Element(cacheKey, (Serializable) result);cache.put(element);}return element.getValue();}/** * 获得cache key的方法,cache key是Cache中一个Element的唯一标识 cache key包括 包名+类名+方法名,如com.co.cache.service.UserServiceImpl.getAllUser */private String getCacheKey(String targetName, String methodName, Object[] arguments){StringBuffer sb = new StringBuffer();sb.append(targetName).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();}/** * implement InitializingBean,检查cache是否为空 */public void afterPropertiesSet() throws Exception{Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");}}

 

public interface TestService{public String getAllObject();public void updateObject(Object Object);}public class TestServiceImpl implements TestService{public String getAllObject(){System.out.println("---TestService:Cache内不存在该element,查找并放入Cache!");return "String";}public void updateObject(Object Object){System.out.println("---TestService:更新了对象,这个Class产生的cache都将被remove!");}}


 

public class MainTest{ public static void main(String args[]) {  String DEFAULT_CONTEXT_FILE = "/applicationContext.xml";  ApplicationContext context = new ClassPathXmlApplicationContext(DEFAULT_CONTEXT_FILE);  TestService testService = (TestService) context.getBean("testService");

  System.out.println("1--第一次查找并创建cache");  String string = testService.getAllObject();  System.out.println(string);    System.out.println("2--在cache中查找");  string = testService.getAllObject();  System.out.println(string);    System.out.println("3--remove cache");  testService.updateObject(null);

  System.out.println("4--需要重新查找并创建cache");  testService.getAllObject();  string = testService.getAllObject();  System.out.println(string); }}

原创粉丝点击