spring + ehcache 实例

简介: 引用:http://blog.csdn.net/hz_chenwenbiaotmb/article/details/5755630 1 spring与ehcache结合使用,需要导入如下的包:ehcache , commons-logging , cglib , asm , spring的jar包具体版本可以选择最新。

引用:http://blog.csdn.net/hz_chenwenbiaotmb/article/details/5755630

1 spring与ehcache结合使用,需要导入如下的包:ehcache , commons-logging , cglib , asm , spring的jar包具体版本可以选择最新。

 

2 spring配置文件applicationContext.xml如下:

 

[xhtml]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.        xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  5.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd  
  6.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"  
  7.        default-lazy-init="true">  
  8.          
  9.     <!-- 在spring里配置cache就和在spring配置数据库一样, -->  
  10.          
  11.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
  12.         <property name="configLocation">    
  13.             <value>ehcache.xml</value>    
  14.         </property>   
  15.     </bean>  
  16.   
  17.     <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">  
  18.         <property name="cacheManager">  
  19.             <ref local="cacheManager"/>  
  20.         </property>  
  21.         <property name="cacheName">  
  22.             <value>com.rmn190.MethodCache</value>  
  23.         </property>  
  24.     </bean>  
  25.     <bean id="methodCacheInterceptor" class="intercepter.MethodCacheInterceptor">  
  26.         <property name="cache">  
  27.             <ref local="methodCache"/>  
  28.         </property>  
  29.     </bean>  
  30.   
  31.     <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  
  32.         <property name="advice">  
  33.             <ref local="methodCacheInterceptor"/>  
  34.         </property>  
  35.         <!-- 下面的配置就使得在数据访问时,cache将拦截从数据库获取的数据,与cache数据比较,如有就不放入cache,没有就放入,更新到数据库去,也是先存入cache,再更新到数据库中去 -->  
  36.         <property name="patterns">  
  37.             <list>  
  38.                 <value>.*getList</value>  
  39.             </list>  
  40.         </property>  
  41.     </bean>  
  42.   
  43.     <bean  id = "personManager" class="org.springframework.aop.framework.ProxyFactoryBean">  
  44.         <property name="target">  
  45.             <!--<bean class="manager.PersonManagerImpl"/>-->  
  46.             <ref local="personManagerTarget"/>  
  47.         </property>  
  48.         <property name="interceptorNames">  
  49.             <list>  
  50.                 <value>methodCachePointCut</value>  
  51.             </list>  
  52.         </property>  
  53.     </bean>  
  54.       
  55.     <bean id = "personManagerTarget" class="manager.PersonManagerImpl"/>  
  56. </beans>  

 

 

ehcache配置文件ehcache.xml如下:

 

[xhtml]  view plain copy
  1. <ehcache>  
  2.   
  3.     <!-- Sets the path to the directory where cache .data files are created.  
  4.   
  5.          If the path is a Java System Property it is replaced by  
  6.          its value in the running VM.  
  7.   
  8.          The following properties are translated:  
  9.          user.home - User's home directory  
  10.          user.dir - User's current working directory  
  11.          java.io.tmpdir - Default temp file path -->  
  12.     <diskStore path="java.io.tmpdir"/>  
  13.   
  14.   
  15.     <!--Default Cache configuration. These will applied to caches programmatically created through  
  16.         the CacheManager.  
  17.   
  18.         The following attributes are required:  
  19.   
  20.         maxElementsInMemory            - Sets the maximum number of objects that will be created in memory  
  21.         eternal(永恒)                        - Sets whether elements are eternal. If eternal,  timeouts are ignored and the  
  22.                                          element is never expired(过期).  
  23.         overflowToDisk                 - Sets whether elements can overflow to disk when the in-memory cache  
  24.                                          has reached the maxInMemory limit.  
  25.   
  26.         The following attributes are optional:  
  27.         timeToIdleSeconds              - Sets the time to idle for an element before it expires.  
  28.                                          i.e. The maximum amount of time between accesses before an element expires  
  29.                                          Is only used if the element is not eternal.  
  30.                                          Optional attribute. A value of 0 means that an Element can idle for infinity.  
  31.                                          The default value is 0.  
  32.         timeToLiveSeconds              - Sets the time to live for an element before it expires.  
  33.                                          i.e. The maximum time between creation time and when an element expires.  
  34.                                          Is only used if the element is not eternal.  
  35.                                          Optional attribute. A value of 0 means that and Element can live for infinity.  
  36.                                          The default value is 0.  
  37.         diskPersistent                 - Whether the disk store persists between restarts of the Virtual Machine.  
  38.                                          The default value is false.  
  39.         diskExpiryThreadIntervalSeconds- The number of seconds between runs of the disk expiry thread. The default value  
  40.                                          is 120 seconds.  
  41.         -->  
  42.   
  43.   
  44. <!-- maxElementsInMemory设定内存中创建对象的最大值 -->  
  45. <!-- eternal设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超 时限制且元素永不消亡。-->  
  46. <!-- overflowToDisk设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘上 -->  
  47. <!-- timeToIdleSeconds设置某个元素消亡前的停顿时间。  也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。  
  48.              这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则 设置该属性也无用)。  
  49.        如果该值是 0 就意味着元素可以停顿无穷长的时间。                                   
  50. -->  
  51. <!-- timeToLiveSeconds为元素设置消亡前的生存时间。 也就是一个元素从构建到消亡的最大时间间隔值。 这只能在元素不是永久驻留时有效。 
  52. -->  
  53. <!-- diskPersistent是否disk store在虚拟机启动时持久化。默认为false -->  
  54. <!-- diskExpiryThreadIntervalSeconds运行disk终结线程的时间,默认为120秒 -->  
  55.   
  56.   
  57.     <defaultCache  
  58.         maxElementsInMemory="10000"   
  59.         eternal="false"   
  60.         overflowToDisk="true"   
  61.         timeToIdleSeconds="500"   
  62.         timeToLiveSeconds="1000"   
  63.         diskPersistent="false"   
  64.         diskExpiryThreadIntervalSeconds="120"/>   
  65.           
  66.     <cache name="com.rmn190.MethodCache"  
  67.             maxElementsInMemory="10"  
  68.             eternal="false"  
  69.             timeToIdleSeconds="200"  
  70.             timeToLiveSeconds="300"  
  71.             overflowToDisk="true"  
  72.             />      
  73.               
  74. </ehcache>  

 

 

4 测试类如下:

主类:

 

[java]  view plain copy
  1. package main;  
  2.   
  3. import java.util.List;  
  4.   
  5. import manager.PersonManagerImpl;  
  6.   
  7. import org.springframework.context.ApplicationContext;  
  8. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  9.   
  10. /* 
  11.  * 当没有导入cglib的jar包时,会抛出如下的异常: 
  12.  * 信息: Initializing EHCache CacheManager 
  13. Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personManager': FactoryBean threw exception on object creation; nested exception is org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces. 
  14. Caused by: org.springframework.aop.framework.AopConfigException: Cannot proxy target class because CGLIB2 is not available. Add CGLIB to the class path or specify proxy interfaces. 
  15.     at org.springframework.aop.framework.DefaultAopProxyFactory.createAopProxy(DefaultAopProxyFactory.java:65) 
  16.     at org.springframework.aop.framework.ProxyCreatorSupport.createAopProxy(ProxyCreatorSupport.java:106) 
  17.     at org.springframework.aop.framework.ProxyFactoryBean.getSingletonInstance(ProxyFactoryBean.java:297) 
  18.     at org.springframework.aop.framework.ProxyFactoryBean.getObject(ProxyFactoryBean.java:227) 
  19.     at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectFromFactoryBean(AbstractBeanFactory.java:1236) 
  20.     at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1207) 
  21.     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:262) 
  22.     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160) 
  23.     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:733) 
  24.     at main.HelloEhcacheSpring.main(HelloEhcacheSpring.java:15) 
  25.  */  
  26.   
  27. /* 
  28.  * 加入cglib,而没加入asm的jar包时,抛出如下异常: 
  29.  * 信息: Initializing EHCache CacheManager 
  30. Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personManager': FactoryBean threw exception on object creation; nested exception is java.lang.NoClassDefFoundError: org/objectweb/asm/Type 
  31. Caused by: java.lang.NoClassDefFoundError: org/objectweb/asm/Type 
  32.     at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180) 
  33.     at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66) 
  34.     at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69) 
  35.     at org.springframework.aop.framework.Cglib2AopProxy.createEnhancer(Cglib2AopProxy.java:224) 
  36.     at org.springframework.aop.framework.Cglib2AopProxy.getProxy(Cglib2AopProxy.java:151) 
  37.     at org.springframework.aop.framework.ProxyFactoryBean.getProxy(ProxyFactoryBean.java:342) 
  38.     at org.springframework.aop.framework.ProxyFactoryBean.getSingletonInstance(ProxyFactoryBean.java:297) 
  39.     at org.springframework.aop.framework.ProxyFactoryBean.getObject(ProxyFactoryBean.java:227) 
  40.     at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectFromFactoryBean(AbstractBeanFactory.java:1236) 
  41.     at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1207) 
  42.     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:262) 
  43.     at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160) 
  44.     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:733) 
  45.     at main.HelloEhcacheSpring.main(HelloEhcacheSpring.java:32) 
  46. Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type 
  47.     at java.net.URLClassLoader$1.run(URLClassLoader.java:200) 
  48.     at java.security.AccessController.doPrivileged(Native Method) 
  49.     at java.net.URLClassLoader.findClass(URLClassLoader.java:188) 
  50.     at java.lang.ClassLoader.loadClass(ClassLoader.java:307) 
  51.     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) 
  52.     at java.lang.ClassLoader.loadClass(ClassLoader.java:252) 
  53.     at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) 
  54.     ... 14 more 
  55.  
  56.  */  
  57.   
  58. /* 
  59.  * 这里使用了ehcache与spring结合,这里并没用用到数据库,用spring只是用来管理bean,这里用ehcache就相当于数据库,存放对象信息 
  60.  */  
  61.   
  62. @SuppressWarnings({"unchecked"})  
  63. public class HelloEhcacheSpring {  
  64.     public static void main(String[] args) {  
  65.         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");  
  66.           
  67.         PersonManagerImpl personManager = (PersonManagerImpl) context.getBean("personManager");//配置了spring就可以从配置文件里找到对应的接口实现类,再生成实例对象,以完成业务处理  
  68.           
  69.         for(int i=0;i<5;i++) {  
  70.             showPersonsInfo(personManager);  
  71.         }  
  72.     }  
  73.     private static void showPersonsInfo(PersonManagerImpl personManager) {  
  74.         //要是没有cache时,那么这里会直接从PersonmanagerImpl类的实例对象获取到数据,这里配置了cache后,就会先跳到cache去更新cache,再往下执行  
  75.         List<String> persons = personManager.getList();  
  76.           
  77.         for(String person : persons) {  
  78.             System.out.println(person);  
  79.         }  
  80.     }  
  81. }  

 

 

数据访问时,触发ehcache的更新:

 

[java]  view plain copy
  1. package intercepter;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. import org.aopalliance.intercept.MethodInterceptor;  
  6. import org.aopalliance.intercept.MethodInvocation;  
  7. import org.springframework.beans.factory.InitializingBean;  
  8.   
  9. import net.sf.ehcache.Cache;  
  10. import net.sf.ehcache.Element;  
  11.   
  12. public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean{  
  13.     private Cache cache;  
  14.   
  15.     public void setCache(Cache cache) {  
  16.         this.cache = cache;  
  17.     }  
  18.       
  19.     /* 
  20.      * 首先有一点要明白的是:invoke的触发都在由于DAO或sevlet的数据访问时才会调用到 
  21.      */  
  22.     //invoke方法会在spring配置文件里的,指明的cache拦截的方法的调用时,自动触发它,如这个项目里,当运行HelloEhcacheSpring.java类时,在showPersonsInfo方法里调用到personManager.getList()方法时,它就会先调到这里来执行,执行完才行下执行它的业务  
  23.     public Object invoke(MethodInvocation invocation) throws Throwable {  
  24.         String targetName = invocation.getThis().getClass().getName();//这个表示哪个类调用(或触发)了这个MethodCacheInterceptor,如里的:manager.PersonMagagerImpl  
  25.         String methodName = invocation.getMethod().getName();//这个表示哪个方法触发了这个类(MethodCacheInterceptor)方法(invoke)的调用,如这里的:getList  
  26.         Object[] arguments = invocation.getArguments();//调用的参数,这里没有参数  
  27.         Object result;  
  28.   
  29.         String cacheKey = getCacheKey(targetName, methodName, arguments);//这里得出的是:manager.PersonManagerImpl.getList  
  30.         Element element = cache.get(cacheKey);  
  31.         if (element == null) {  
  32.             // call target/sub-interceptor  
  33.             result = invocation.proceed();//这个就是调用数据访问方法,如这里是调用manager.PersonManagerImpl.getList(),并用result保存执行的结果(数据访问的结果),如这里调用了getList()方法,会先打印出"get Person from DB" ,然后将结果集放入到result里面去,这里由于使用的是自己配置只能放入10个元素的ehcache,所以这里的result是ArrayList<E> ,它里面存放的是elementData[10],并将getList得到的结果放入到elementData里面去了  
  34.             System.out.println("set into cache");  
  35.             // cache method result  
  36.             //下面方法执行后,将cacheKey与数据集连起来,cacheKey是用来标识这个element的标志,我们可以有多个element(各自是来自不同的数据访问方法而形成的),区分它们就是用cacheKey,  
  37.             element = new Element(cacheKey, (Serializable) result);//这里的新生成后的element,含有cacheKey,还在element创建时间,访问时间,还有命令次数等cache的属性,我觉得它就像是一个小cache一样,下次要不要更新它就要看它的这些属性来决定。  
  38.             cache.put(element);//放入cache中  
  39.         }  
  40.         System.out.println("out cache");//完成cache操作  
  41.         return element.getValue();  
  42.     }  
  43.   
  44.       
  45.     private String getCacheKey(String targetName, String methodName,  
  46.             Object[] arguments) {  
  47.         StringBuffer sb = new StringBuffer();  
  48.         sb.append(targetName).append(".").append(methodName);  
  49.         if ((arguments != null) && (arguments.length != 0)) {  
  50.             for (int i = 0; i < arguments.length; i++) {  
  51.                 sb.append(".").append(arguments[i]);  
  52.             }  
  53.         }  
  54.   
  55.         return sb.toString();  
  56.     }  
  57.   
  58.     public void afterPropertiesSet() throws Exception {  
  59.         if(null == cache) {  
  60.             throw new IllegalArgumentException("Cache should not be null.");  
  61.         }  
  62.     }  
  63.   
  64. }  

 

 

数据提供类:

 

[java]  view plain copy
  1. package manager;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. @SuppressWarnings("unchecked")  
  7. public class PersonManagerImpl {  
  8.       
  9.     private static List persons;  
  10.   
  11.     static {  
  12.         persons = new ArrayList();  
  13.           
  14.         persons.add("Wang");  
  15.         persons.add("zang");  
  16.         persons.add("Li");  
  17.         persons.add("song");  
  18.         persons.add("yan");  
  19.     }  
  20.       
  21.     public List getList() {  
  22.         System.out.println("getPerons from DB");  
  23.         return persons;  
  24.     }  
  25.       
  26. }  

 

相关文章
|
1月前
|
监控 Java 数据处理
【Spring云原生】Spring Batch:海量数据高并发任务处理!数据处理纵享新丝滑!事务管理机制+并行处理+实例应用讲解
【Spring云原生】Spring Batch:海量数据高并发任务处理!数据处理纵享新丝滑!事务管理机制+并行处理+实例应用讲解
|
Java 微服务 Spring
从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(六)(优化篇)开发篇-如何解决微服务开发环境请求实例转发到别人机器问题
从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(六)(优化篇)开发篇-如何解决微服务开发环境请求实例转发到别人机器问题
从0到1 手把手搭建spring cloud alibaba 微服务大型应用框架(六)(优化篇)开发篇-如何解决微服务开发环境请求实例转发到别人机器问题
|
1天前
|
安全 Java Maven
[AIGC] Spring Boot中的切面编程和实例演示
[AIGC] Spring Boot中的切面编程和实例演示
|
3月前
|
消息中间件 Java Spring
RabbitMQ各种模式的含义与Spring Boot实例详解
RabbitMQ各种模式的含义与Spring Boot实例详解
36 0
|
8月前
|
安全 Java Spring
Spring中的Aop简单实例讲解
Spring中的Aop简单实例讲解
78 0
|
4月前
|
消息中间件 Java Spring
Spring Boot中异步消息JMS的讲解与通信实例
Spring Boot中异步消息JMS的讲解与通信实例
43 1
|
4月前
|
SQL Java Spring
Spring Data JPA之JpaSpecificationExecutor复杂动态查询实例
Spring Data JPA之JpaSpecificationExecutor复杂动态查询实例
32 0
|
4月前
|
XML Java 数据库连接
Hibernate与Spring整合实践实例
Hibernate与Spring整合实践实例
40 0
|
4月前
|
XML 前端开发 Java
Spring MVC - context:component-scan实现原理与实例
Spring MVC - context:component-scan实现原理与实例
24 0
|
5月前
|
XML Java 数据库连接
Mybatis - 集成Spring实例详解
Mybatis - 集成Spring实例详解
30 0