- 浏览: 119962 次
- 性别:
- 来自: 广州
-
文章分类
最新评论
-
Kevin_jiang2011:
能直接在,代码里面配置吗?
Spring+CXF配置HTTP代理访问Internet -
xbiji:
不能用啊!!!!!!!!!!!!!!!!!!!!!!1
JQuery获取页面高度,页面宽度,窗口高度,窗口宽度 -
ben_liang:
# <http-conf:proxyAuthoriza ...
Spring+CXF配置HTTP代理访问Internet -
navy0168:
package com;import java.io. ...
解压缩
转自:http://blog.csdn.net/liuzhenwen/archive/2009/03/12/3983952.aspx
需要使用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
- 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 Object invoke(MethodInvocation invocation) 中,完成了搜索Cache/新建cache的功能。
- Element element = cache.get(cacheKey);
这句代码的作用是获取cache中的element,如果cacheKey所对应的element不存在,将会返回一个null值
-
result = invocation.proceed();
这句代码的作用是获取所拦截方法的返回值,详细请查阅AOP相关文档。
随后,再建立一个拦截器MethodCacheAfterAdvice,作用是在用户进行create/update/delete操作时来刷新 /remove相关cache内容,这个拦截器实现了AfterReturningAdvice接口,将会在所拦截的方法执行后执行在public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)方法中所预定的操作
- 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." );
- }
-
}
上面的代码很简单,实现了afterReturning方法实现自AfterReturningAdvice接口,方法中所定义的内容将会在目标方法执行后执行,在该方法中
- String className = arg3.getClass().getName();
的作用是获取目标class的全名,如:com.co.cache.test.TestServiceImpl,然后循环cache的key list,remove cache中所有和该class相关的element。
随后,开始配置ehCache的属性,ehCache需要一个xml文件来设置ehCache相关的一些属性,如最大缓存数量、cache刷新的时间等等.
ehcache.xml
- <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>
配置每一项的详细作用不再详细解释,有兴趣的请google下 ,这里需要注意一点defaultCache标签定义了一个默认的Cache,这个Cache是不能删除的,否则会抛出No default cache is configured异常。另外,由于使用拦截器来刷新Cache内容,因此在定义cache生命周期时可以定义较大的数值,timeToIdleSeconds="300000" timeToLiveSeconds="600000",好像还不够大?
然后,在将Cache和两个拦截器配置到Spring,这里没有使用2.0里面AOP的标签。
cacheContext.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="defaultCacheManager" class = "org.springframework.cache.ehcache.EhCacheManagerFactoryBean" >
- <property name="configLocation" >
- <value>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>
上面的代码最终创建了两个"切入点",methodCachePointCut和methodCachePointCutAdvice,分别用于拦截不同方法名的方法,可以根据需要任意增加所需要拦截方法的名称。
需要注意的是
- <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>
如果cacheName属性内设置的name在ehCache.xml中无法找到,那么将使用默认的cache(defaultCache标签定义).
事实上到了这里,一个简单的Spring + ehCache Framework基本完成了,为了测试效果,举一个实际应用的例子,定义一个TestService和它的实现类TestServiceImpl,里面包含
两个方法getAllObject()和updateObject(Object Object),具体代码如下
TestService.java
- package com.co.cache.test;
- import java.util.List;
- public interface TestService {
- public List getAllObject();
- public void updateObject(Object Object);
-
}
TestServiceImpl.java
- 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!" );
- }
-
}
使用Spring提供的AOP进行配置
applicationContext.xml
- <?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" class = "com.co.cache.test.TestServiceImpl" />
- <bean id="testService" class = "org.springframework.aop.framework.ProxyFactoryBean" >
- <property name="target" >
- <ref local="testServiceTarget" />
- </property>
- <property name="interceptorNames" >
- <list>
- <value>methodCachePointCut</value>
- <value>methodCachePointCutAdvice</value>
- </list>
- </property>
- </bean>
-
</beans>
这里一定不能忘记import cacheContext.xml文件,不然定义的两个拦截器就没办法使用了。
最后,写一个测试的代码
MainTest.java
- 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!
大功告成 .可以看到,第一步执行getAllObject(),执行TestServiceImpl内的方法,并创建了cache,在第二次执行 getAllObject()方法时,由于cache有该方法的缓存,直接从cache中get出方法的结果,所以没有打印出 TestServiceImpl中的内容,而第三步,调用了updateObject方法,和TestServiceImpl相关的cache被 remove,所以在第四步执行时,又执行TestServiceImpl中的方法,创建Cache。
网上也有不少类似的例子,但是很多都不是很完备,自己参考了一些例子的代码,其实在spring-modules中也提供了对几种cache的支持,ehCache,OSCache,JBossCache这些,看了一下,基本上都是采用类似的方式,只不过封装的更完善一些,主要思路也还是 Spring的AOP,有兴趣的可以研究一下。
hibernate缓存
1.在applicationContext.xml中引入
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="${hibernate.config.location}" /> <property name="mappingLocations"> <list> <value>classpath:/com/mysougou/mtmibp/center/core/entity/*.hbm.xml</value> <value>classpath:/com/mysougou/mtmibp/cms/cms/entity/*.hbm.xml</value> <value>classpath:/com/mysougou/mtmibp/cms/article/entity/*.hbm.xml</value> <value>classpath:/com/mysougou/mtmibp/cms/download/entity/*.hbm.xml</value> <value>classpath:/com/mysougou/mtmibp/cms/auxiliary/entity/*.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <!--hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect--> <!--hibernate.dialect=org.hibernate.dialect.SQLServerDialect--> <value> hibernate.dialect=org.hibernate.dialect.SQLServerDialect hibernate.show_sql=true hibernate.format_sql=false hibernate.query.substitutions=true 1, false 0 hibernate.jdbc.batch_size=20 hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider hibernate.cache.provider_configuration_file_resource_path=/ehcache-hibernate.xml </value> </property> <property name="entityInterceptor"> <ref local="treeInterceptor"/> </property> </bean>
ehcache-hibernate.xml
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <diskStore path="java.io.tmpdir/mysougou2/hibernate"/> <cacheManagerEventListenerFactory class="" properties=""/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/> <cache name="com.mysougou.mtmibp.core.entity.Website" maxElementsInMemory="100" eternal="true" overflowToDisk="true"/> <cache name="com.mysougou.mtmibp.core.entity.Global" maxElementsInMemory="1" eternal="true" overflowToDisk="true"/> <cache name="com.mysougou.mtmibp.core.entity.Function" maxElementsInMemory="3000" eternal="true" overflowToDisk="true"/> <cache name="com.mysougou.mtmibp.core.entity.Function.child" maxElementsInMemory="3000" eternal="true" overflowToDisk="true"/> </ehcache>
发表评论
-
spring定时调度
2010-11-18 15:11 1072转自:http://www.360doc.com/conten ... -
IntrospectorCleanupListener 简介
2010-07-30 17:08 1056转自:http://wenth.iteye.com/blog/ ... -
Spring源码分析
2010-07-28 10:55 856http://jiwenke.iteye.com/?page= ... -
关于spring声明式事务,事务无法回滚的总结
2010-07-28 09:58 1527转:http://hi.baidu.com/hougbin/b ... -
Spring+CXF配置HTTP代理访问Internet
2010-07-28 09:25 3224转:http://www.blogjava.net/Hafey ... -
小探Spring 2.5 MVC中基于注解的Controller控制器
2010-07-21 15:09 909转自:http://dakulaliu.iteye ...
相关推荐
Spring AOP 和 EhCache 结合使用提供了一个简单而有效的缓存解决方案,主要目的是优化系统性能,减少对数据库的频繁访问。下面将详细解释这个解决方案的关键组成部分。 首先,EhCache 是一个广泛使用的开源 Java ...
当我们谈论“Spring + Ehcache + Redis”两级缓存时,我们实际上是在讨论如何在Java环境中利用Spring框架来集成Ehcache作为本地缓存,并利用Redis作为分布式二级缓存,构建一个高效且可扩展的缓存解决方案。...
本文将深入探讨如何结合Spring AOP与EhCache实现一个简单的缓存实例,以便优化Java应用的运行效率。 首先,让我们了解Spring AOP。Spring AOP是Spring框架的一部分,它允许我们在不修改业务代码的情况下,通过定义...
EhCache是Java的分布式缓存解决方案,它能够存储对象并提高应用程序的响应速度。在Web应用中,EhCache可以用于缓存静态内容或频繁查询的结果,减少对数据库的访问,从而提升性能。 Licence管理通常涉及到软件的授权...
Ehcache 则是一款流行的Java缓存解决方案,它能够有效提升应用的性能,尤其是在数据库读取操作频繁的情况下。 在这个"spring+ehcache示例整合Demo"中,我们将会探讨如何将Ehcache集成到Spring框架中,以实现高效的...
在IT行业中,Spring、iBatis和Ehcache是三个非常重要的开源框架,它们分别用于企业级应用的依赖注入、数据库操作和缓存管理。这个"spring+ibatis+ehcache整合例子"是一个完整的示例项目,展示了如何将这三个框架无缝...
在IT行业中,构建高效、可扩展的Web应用是至关重要的,而"hibernate4+spring4+springmvc+ehcache+自己写的cache系统"是一个常见的技术栈,用于实现这样的目标。这个组合提供了完整的数据持久化、服务层管理、前端...
总之,Spring的AOP和EHCache的集成,为我们的Java应用提供了一种便捷、高效的缓存解决方案。通过合理地使用注解和自定义切面,我们可以创建出性能优异、易于维护的应用程序。在实际开发过程中,还需要注意缓存的一致...
而Ehcache则是一个高效的缓存解决方案,能够提高应用性能,减少对数据库的访问。 在"Spring+Hibernate+ehcache整合"项目中,开发者已经完成了一个将这三个框架集成的基础工程。虽然Struts没有被明确提及,但通常在...
Ehcache作为一款流行的开源缓存解决方案,因其轻量级、高性能和易于集成的特点,常被广泛应用于Spring框架中。本篇文章将详细介绍如何在Spring项目中集成Ehcache,以及如何通过Spring的AOP(面向切面编程)实现方法...
这个实例演示了如何利用Maven作为构建工具,Spring作为核心框架,Ehcache作为缓存解决方案,以及Spring JDBC处理数据库交互。 **Maven** 是一个项目管理和综合工具,它管理项目的构建、依赖关系和生命周期。在本...
此外,为了实现Ehcache的分布式特性,可以使用如 Hazelcast 或 Redis 等分布式缓存解决方案,将缓存数据同步到多个节点,进一步提升系统的可扩展性和可用性。 总之,Spring MVC、MyBatis和Ehcache的组合为开发高效...
8. slf4j-api.jar:简单日志门面,Spring Security和Ehcache可能用到的日志库。 9. logback-classic.jar:一种实现SLF4J的日志框架,用于记录系统日志。 这些jar包是构建基于Spring和Acegi Security的安全框架所...
7. **Ehcache缓存**:Ehcache是Java的一个流行缓存解决方案,可以用于存储和检索经常访问的数据,提高系统性能。在Web应用中,Ehcache可以缓存数据库查询结果或计算结果,减少对数据库的访问压力。 8. **DOM4J**:...
它支持分布式缓存,若需要更高性能或更复杂的缓存策略,可以替换为Redis等其他缓存解决方案。 6. **JCaptcha**: JCaptcha是一个简单的图形验证码生成框架,用于防止恶意自动化的机器人程序进行用户验证。它生成的...
本代码通过使用spring aop+ehcache的技术,实现了方法级别的查询缓存,主要原理是 方法的完整路径+方法参数值,作为key,放入cache中,下次访问时先判断cache中是否有该key.
Ehcache是基于内存的缓存解决方案,它可以在内存中存储经常访问的数据,减少对数据库的访问,从而提高应用的响应速度。Ehcache可以集成到Spring中,通过配置文件(ehcache.xml)设置缓存策略,如缓存大小、过期时间...
Ehcache则是一款广泛使用的开源缓存解决方案,用于提高应用程序性能,减少数据库负载。本篇文章将详细探讨如何在Spring框架中集成并实现基于方法的缓存机制,利用Ehcache来优化数据访问。 首先,我们需要理解Spring...