Spring + ehCache实现缓存
转贴
Spring AOP+ehCache简单缓存系统解决方案
需要使用Spring来实现一个Cache简单的解决方案,具体需求如下:使用任意一个现有开源Cache Framework,要求可以Cache系统中Service或则DAO层的get/find等方法返回结果,如果数据更新(使用Create/update/delete方法),则刷新cache中相应的内容。
根据需求,计划使用Spring AOP + ehCache来实现这个功能,采用ehCache原因之一是Spring提供了ehCache的支持,至于为何仅仅支持ehCache而不支持osCache和JBossCache无从得知(Hibernate???),但毕竟Spring提供了支持,可以减少一部分工作量:)。二是后来实现了OSCache和JBoss Cache的方式后,经过简单测试发现几个Cache在效率上没有太大的区别(不考虑集群),决定采用ehCahce。
AOP嘛,少不了拦截器,先创建一个实现了MethodInterceptor接口的拦截器,用来拦截Service/DAO的方法调用,拦截到方法后,搜索该方法的结果在cache中是否存在,如果存在,返回cache中的缓存结果,如果不存在,返回查询数据库的结果,并将结果缓存到cache中。
MethodCacheInterceptor.java
Java代码
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."); } }
Element element = cache.get(cacheKey);
result = invocation.proceed();
package com.co.cache.ehcache; import java.lang.reflect.Method; import java.util.List; import net.sf.ehcache.Cache; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aop.AfterReturningAdvice; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.Assert; 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."); } }
<ehcache> <diskStore path="c:\\myapp\\cache"/> <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>
<?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="defaultCacheManager" /> </property> </bean> <!-- flush cache拦截器 --> <bean id="methodCacheAfterAdvice" /> </property> </bean> <bean id="methodCachePointCut" name="code"><bean id="ehCache" name="code">package com.co.cache.test; import java.util.List; public interface TestService { public List getAllObject(); public void updateObject(Object Object); }
package com.co.cache.test; import java.util.List; public class TestServiceImpl implements TestService { public List getAllObject() { System.out.println("---TestService:Cache内不存在该element,查找并放入Cache!"); return null; } public void updateObject(Object Object) { System.out.println("---TestService:更新了对象,这个Class产生的cache都将被remove!"); } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <import resource="cacheContext.xml"/> <bean id="testServiceTarget" name="code">package com.co.cache.test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; 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"); testService.getAllObject(); System.out.println("2--在cache中查找"); testService.getAllObject(); System.out.println("3--remove cache"); testService.updateObject(null); System.out.println("4--需要重新查找并创建cache"); testService.getAllObject(); } }
1--第一次查找并创建cache ---TestService:Cache内不存在该element,查找并放入Cache! 2--在cache中查找 3--remove cache ---TestService:更新了对象,这个Class产生的cache都将被remove! 4--需要重新查找并创建cache ---TestService:Cache内不存在该element,查找并放入Cache!