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 [code] 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."); } } [/code] 上面的代码中可以看到,在方法public Object invoke(MethodInvocation invocation) 中,完成了搜索Cache/新建cache的功能。 [code] Element element = cache.get(cacheKey); [/code] 这句代码的作用是获取cache中的element,如果cacheKey所对应的element不存在,将会返回一个null值 [code] result = invocation.proceed(); [/code] 这句代码的作用是获取所拦截方法的返回值,详细请查阅AOP相关文档。 随后,再建立一个拦截器MethodCacheAfterAdvice,作用是在用户进行create/update/delete操作时来刷新/remove相关cache内容,这个拦截器实现了AfterReturningAdvice接口,将会在所拦截的方法执行后执行在public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)方法中所预定的操作 [code] 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 [/code] 配置每一项的详细作用不再详细解释,有兴趣的请google下 :P ,这里需要注意一点defaultCache标签定义了一个默认的Cache,这个Cache是不能删除的,否则会抛出No default cache is configured异常。另外,由于使用拦截器来刷新Cache内容,因此在定义cache生命周期时可以定义较大的数值,timeToIdleSeconds="300000" timeToLiveSeconds="600000",好像还不够大? :cry: 然后,在将Cache和两个拦截器配置到Spring,这里没有使用2.0里面AOP的标签。 cacheContext.xml [code] ehcache.xml DEFAULT_CACHE .*find.* .*get.* .*create.* .*update.* .*delete.* [/code] 上面的代码最终创建了两个"切入点",methodCachePointCut和methodCachePointCutAdvice,分别用于拦截不同方法名的方法,可以根据需要任意增加所需要拦截方法的名称。 需要注意的是 [code] DEFAULT_CACHE [/code] 如果cacheName属性内设置的name在ehCache.xml中无法找到,那么将使用默认的cache(defaultCache标签定义). 事实上到了这里,一个简单的Spring + ehCache Framework基本完成了,为了测试效果,举一个实际应用的例子,定义一个TestService和它的实现类TestServiceImpl,里面包含 两个方法getAllObject()和updateObject(Object Object),具体代码如下 TestService.java [code] package com.co.cache.test; import java.util.List; public interface TestService { public List getAllObject(); public void updateObject(Object Object); } [/code] TestServiceImpl.java [code] 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!"); } } [/code] 使用Spring提供的AOP进行配置 applicationContext.xml [code] methodCachePointCut methodCachePointCutAdvice [/code] 这里一定不能忘记import cacheContext.xml文件,不然定义的两个拦截器就没办法使用了。 最后,写一个测试的代码 MainTest.java [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(); } } [/code] 运行,结果如下 [code] 1--第一次查找并创建cache ---TestService:Cache内不存在该element,查找并放入Cache! 2--在cache中查找 3--remove cache ---TestService:更新了对象,这个Class产生的cache都将被remove! 4--需要重新查找并创建cache ---TestService:Cache内不存在该element,查找并放入Cache! [/code] 大功告成 :D .可以看到,第一步执行getAllObject(),执行TestServiceImpl内的方法,并创建了cache,在第二次执行getAllObject()方法时,由于cache有该方法的缓存,直接从cache中get出方法的结果,所以没有打印出TestServiceImpl中的内容,而第三步,调用了updateObject方法,和TestServiceImpl相关的cache被remove,所以在第四步执行时,又执行TestServiceImpl中的方法,创建Cache。 网上也有不少类似的例子,但是很多都不是很完备,自己参考了一些例子的代码,其实在spring-modules中也提供了对几种cache的支持,ehCache,OSCache,JBossCache这些,看了一下,基本上都是采用类似的方式,只不过封装的更完善一些,主要思路也还是Spring的AOP,有兴趣的可以研究一下。
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultCacheManager' defined in class path resource : Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: edu/emory/mathcs/backport/java/util/concurrent/BlockingQueue Caused by: java.lang.NoClassDefFoundError: edu/emory/mathcs/backport/java/util/concurrent/BlockingQueue 我复制你的代码,却报这个异常? ……谢谢……
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultCacheManager' defined in class path resource : Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: edu/emory/mathcs/backport/java/util/concurrent/BlockingQueue Caused by: java.lang.NoClassDefFoundError: edu/emory/mathcs/backport/java/util/concurrent/BlockingQueue 我照着你那做,却报这个异常?why?
感谢回复,实际上Cache并不是在任何场合都适用的,我想最好用在一些访问频率高、刷新频率低的操作上面,如访问获取用户列表这些,有些时候,例如在多参数组合查询、复杂对象为参数的查询方法中并不适用,命中率太低,而且还会其他一些问题。
CRUD 层的 cache 存取和刷新,个人觉得没必要做这么一大堆事情。
原因其一:CRUD层基于类名+方法名+参数来做cache key,实际生产的大并发环境下,命中率很低,尤其是在内存有限的情况下如果又做了 cache size 的控制,命中率更低了。
其二:基于类名+方法名+参数做 cache key 这样的缓存存取机制,iBatis 白送一个,添一个属性就打开了,而且允许你在多个cache框架间随意切换。想出好的缓存效果,这个功能算是一个鸡肋。我一般打开就不管他了。基于对象或者静态文本的缓存另外再做。
是的,项目比较复杂,不过在项目中已经大量的使用了AOP在service或DAO层,所以如果应用cache到系统中,仅仅需要写好拦截器并配置代理就可以。
看了你的Cache方案,很不错 :idea: 。
AOP在拦截过程中可以拦截到方法参数,不过如果参数为复杂对象,在拦截方法中就没办法确定所拦截的参数对象状态是否相同 :x :?: ,实际项目中已经解决了,有时间我发上来。
我用ReadWriteLock配合Proxy在service层实现了针对少量数据的缓存:
http://dev2dev.bea.com.cn/techdoc/2007/07/java-soa-ReadWriteLock.html
不用aop是因为很难得到方法参数,而且失去了编译期的强类型检查。
从传统角度来说,在你的DAO或者SERVICE层需要CACHE支持的做个CACHE层。。。但看起来你的系统比较复杂,可能改动会太多?
楼上的XD有什么好的想法一起讨论讨论?多谢!
有意思, 但为什么要用AOP呢? dynamic AOP执行效率慢啊.
用SpringModule里面的SpringCache吧,呵呵
这仅仅是一个简单的解决方案,实际项目中代码比较复杂,不太好描述,这算一个简化的版本吧,只是说明设计的思路。
方法结果的cache应该和对象在不在一个class没有太大关系吧,可以将拦截器配置在service层,拦截service的结果并缓存。
从上面代码可以看到,实际上参数(Object arguments)是经过处理的。
好贴,很详细。