`
newleague
  • 浏览: 1474038 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

Spring中AOP实现EHCache的整合(一)

阅读更多

在项目中使用缓存我OSCache,今天有时间将所有的EHCache的缓存的应用关注一下。首先我们看看Spring和EHCache采用AOP实现的缓存实现。

 

1.首先使用EHCache编写EHCache的配置文件。

Java代码 复制代码 收藏代码
  1. <ehcache>   
  2.      <diskStore path="java.io.tmpdir" />   
  3.      <defaultCache maxElementsInMemory="10000" eternal="false"  
  4.          timeToIdleSeconds="2" timeToLiveSeconds="5" overflowToDisk="true"  
  5.          maxElementsOnDisk="10000000" diskPersistent="false"  
  6.          diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />   
  7.      <cache name="testCache" maxElementsInMemory="10000"  
  8.          maxElementsOnDisk="1000" eternal="false" overflowToDisk="false"  
  9.          diskSpoolBufferSizeMB="20" timeToIdleSeconds="60" timeToLiveSeconds="3600"  
  10.         memoryStoreEvictionPolicy="LFU" />   
  11. </ehcache>  
<ehcache>
     <diskStore path="java.io.tmpdir" />
     <defaultCache maxElementsInMemory="10000" eternal="false"
         timeToIdleSeconds="2" timeToLiveSeconds="5" overflowToDisk="true"
         maxElementsOnDisk="10000000" diskPersistent="false"
         diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU" />
     <cache name="testCache" maxElementsInMemory="10000"
         maxElementsOnDisk="1000" eternal="false" overflowToDisk="false"
         diskSpoolBufferSizeMB="20" timeToIdleSeconds="60" timeToLiveSeconds="3600"
        memoryStoreEvictionPolicy="LFU" />
</ehcache>

 2.编写AOP的方法拦截器,此处采用环绕通知的方式实现方法拦截。

Java代码 复制代码 收藏代码
  1. package com.easyway.ecache.service;   
  2. import java.io.Serializable;   
  3.   
  4. import net.sf.ehcache.Cache;   
  5. import net.sf.ehcache.Element;   
  6.   
  7. import org.aopalliance.intercept.MethodInterceptor;   
  8. import org.aopalliance.intercept.MethodInvocation;   
  9. import org.apache.commons.logging.Log;   
  10. import org.apache.commons.logging.LogFactory;   
  11. import org.springframework.beans.factory.InitializingBean;   
  12. /**  
  13.  * AOP方法拦截实现缓存的更新的  
  14.  *   
  15.  * MethodInterceptor:在方法调用会自动调用  
  16.  * InitializingBean:系统初始化时会自动初始化此类的特定的方法afterPropertiesSet()  
  17.  * @author longgangbai  
  18.  *  
  19.  */  
  20. public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean{    
  21.     private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);      
  22.          
  23.   
  24.         private Cache cache;      
  25.          
  26.         public void setCache(Cache cache) {      
  27.             this.cache = cache;      
  28.         }      
  29.               
  30.         //invoke方法会在spring配置文件里的,指明的cache拦截的方法的调用时,自动触发它,如这个项目里,   
  31.         //当运行HelloEhcacheSpring.java类时,在showPersonsInfo方法里调用到personManager.getList()方法时,   
  32.         //它就会先调到这里来执行,执行完才行下执行它的业务      
  33.         public Object invoke(MethodInvocation invocation) throws Throwable {      
  34.             //这个表示哪个类调用(或触发)了这个MethodCacheInterceptor,   
  35.             String targetName = invocation.getThis().getClass().getName();   
  36.             //这个表示哪个方法触发了这个类(MethodCacheInterceptor)方法(invoke)的调用,   
  37.             String methodName = invocation.getMethod().getName();   
  38.             //调用的参数,这里没有参数      
  39.             Object[] arguments = invocation.getArguments();   
  40.             Object result;      
  41.          
  42.             //这里得出的是:manager.PersonManagerImpl.getList      
  43.             String cacheKey = getCacheKey(targetName, methodName, arguments);   
  44.             Element element = cache.get(cacheKey);      
  45.             if (element == null) {      
  46.                 // call target/sub-interceptor      
  47.                 //这个就是调用数据访问方法,   
  48.                 result = invocation.proceed();   
  49.                 //如这里调用了getList()方法,会先打印出"get Person from DB" ,   
  50.                 //然后将结果集放入到result里面去,这里由于使用的是自己配置只能放入10个元素的ehcache,   
  51.                 //所以这里的result是ArrayList<E> ,它里面存放的是elementData[10],并将getList得到的结果放入到elementData里面去了      
  52.                 System.out.println("set into cache");      
  53.                 // cache method result      
  54.                 //下面方法执行后,将cacheKey与数据集连起来,cacheKey是用来标识这个element的标志,我们可以有多个element(各自是来自不同的数据访问方法而形成的),区分它们就是用cacheKey,      
  55.                 //这里的新生成后的element,含有cacheKey,还在element创建时间,访问时间,还有命令次数等cache的属性,我觉得它就像是一个小cache一样,下次要不要更新它就要看它的这些属性来决定。      
  56.                 element = new Element(cacheKey, (Serializable) result);   
  57.                 //放入cache中      
  58.                 cache.put(element);   
  59.             }else{   
  60.                 logger.debug("come from cache ...!");   
  61.             }      
  62.             //完成cache操作      
  63.             System.out.println("out cache");   
  64.             return element.getValue();      
  65.         }      
  66.          
  67.         /**  
  68.          * 缓存特定的类:  
  69.          * @param targetName  
  70.          * @param methodName  
  71.          * @param arguments  
  72.          * @return  
  73.          */  
  74.         private String getCacheKey(String targetName, String methodName,      
  75.                 Object[] arguments) {      
  76.             StringBuffer sb = new StringBuffer();      
  77.             sb.append(targetName).append(".").append(methodName);      
  78.             if ((arguments != null) && (arguments.length != 0)) {      
  79.                 for (int i = 0; i < arguments.length; i++) {      
  80.                     sb.append(".").append(arguments[i]);      
  81.                 }      
  82.             }      
  83.             return sb.toString();      
  84.         }      
  85.          
  86.         /**  
  87.          * 初始化时调用  
  88.          */  
  89.         public void afterPropertiesSet() throws Exception {      
  90.             if(null == cache) {      
  91.                 throw new IllegalArgumentException("Cache should not be null.");      
  92.             }      
  93.         }      
  94.          
  95.     }    
package com.easyway.ecache.service;
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;
/**
 * AOP方法拦截实现缓存的更新的
 * 
 * MethodInterceptor:在方法调用会自动调用
 * InitializingBean:系统初始化时会自动初始化此类的特定的方法afterPropertiesSet()
 * @author longgangbai
 *
 */
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;   
	    }   
	       
	    //invoke方法会在spring配置文件里的,指明的cache拦截的方法的调用时,自动触发它,如这个项目里,
	    //当运行HelloEhcacheSpring.java类时,在showPersonsInfo方法里调用到personManager.getList()方法时,
	    //它就会先调到这里来执行,执行完才行下执行它的业务   
	    public Object invoke(MethodInvocation invocation) throws Throwable {   
	    	//这个表示哪个类调用(或触发)了这个MethodCacheInterceptor,
	        String targetName = invocation.getThis().getClass().getName();
	        //这个表示哪个方法触发了这个类(MethodCacheInterceptor)方法(invoke)的调用,
	        String methodName = invocation.getMethod().getName();
	        //调用的参数,这里没有参数   
	        Object[] arguments = invocation.getArguments();
	        Object result;   
	  
	        //这里得出的是:manager.PersonManagerImpl.getList   
	        String cacheKey = getCacheKey(targetName, methodName, arguments);
	        Element element = cache.get(cacheKey);   
	        if (element == null) {   
	            // call target/sub-interceptor   
	        	//这个就是调用数据访问方法,
	            result = invocation.proceed();
	            //如这里调用了getList()方法,会先打印出"get Person from DB" ,
	            //然后将结果集放入到result里面去,这里由于使用的是自己配置只能放入10个元素的ehcache,
	            //所以这里的result是ArrayList<E> ,它里面存放的是elementData[10],并将getList得到的结果放入到elementData里面去了   
	            System.out.println("set into cache");   
	            // cache method result   
	            //下面方法执行后,将cacheKey与数据集连起来,cacheKey是用来标识这个element的标志,我们可以有多个element(各自是来自不同的数据访问方法而形成的),区分它们就是用cacheKey,   
	            //这里的新生成后的element,含有cacheKey,还在element创建时间,访问时间,还有命令次数等cache的属性,我觉得它就像是一个小cache一样,下次要不要更新它就要看它的这些属性来决定。   
	            element = new Element(cacheKey, (Serializable) result);
	            //放入cache中   
	            cache.put(element);
	        }else{
	        	logger.debug("come from cache ...!");
	        }   
	        //完成cache操作   
	        System.out.println("out cache");
	        return element.getValue();   
	    }   
	  
	    /**
	     * 缓存特定的类:
	     * @param targetName
	     * @param methodName
	     * @param arguments
	     * @return
	     */
	    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();   
	    }   
	  
	    /**
	     * 初始化时调用
	     */
	    public void afterPropertiesSet() throws Exception {   
	        if(null == cache) {   
	            throw new IllegalArgumentException("Cache should not be null.");   
	        }   
	    }   
	  
	}  


 

3.Spring的关于缓存的配置类似事物的配置:

Java代码 复制代码 收藏代码
  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.     <!--配置缓存管理器 -->     
  10.     <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">     
  11.         <property name="configLocation">        
  12.             <value>ehcache.xml</value>        
  13.         </property>       
  14.     </bean>     
  15.        
  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.easyway.MethodCache</value>     
  23.         </property>     
  24.     </bean>     
  25.        
  26.     <!-- 自定义缓存拦截器 -->   
  27.     <bean id="methodCacheInterceptor" class="com.easyway.ecache.service.MethodCacheInterceptor">     
  28.         <property name="cache">     
  29.             <ref local="methodCache"/>     
  30.         </property>     
  31.     </bean>     
  32.        
  33.     <!-- 自定义拦截器 -->   
  34.     <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">     
  35.         <property name="advice">     
  36.             <ref local="methodCacheInterceptor"/>     
  37.         </property>     
  38.         <!-- 下面的配置就使得在数据访问时,cache将拦截从数据库获取的数据,与cache数据比较,如有就不放入cache,没有就放入,更新到数据库去,也是先存入cache,再更新到数据库中去 -->     
  39.         <property name="patterns">     
  40.             <list>     
  41.                 <value>.*getServiceName</value>    
  42.                 <value>.*testMethod</value>     
  43.             </list>     
  44.         </property>     
  45.     </bean>     
  46.     <!-- 声明一个服务 -->   
  47.        
  48.     <bean id = "ticketServiceTarget"  class="com.easyway.ecache.service.TicketService" />     
  49.        
  50.     <!-- 相关的服务 -->   
  51.      <bean id="ticketService"  
  52.        class="org.springframework.aop.framework.ProxyFactoryBean">   
  53.        <property name="target">     
  54.             <ref local="ticketServiceTarget"/>     
  55.         </property>     
  56.         <property name="interceptorNames">     
  57.             <list>     
  58.                 <value>methodCachePointCut</value>     
  59.             </list>     
  60.         </property>     
  61.      </bean>   
  62.         
  63. </beans>    
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd   
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd   
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"   
       default-lazy-init="true">  
    
    <!--配置缓存管理器 -->  
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">  
        <property name="configLocation">     
            <value>ehcache.xml</value>     
        </property>    
    </bean>  
    
    <!-- 创建缓存的工厂的应用 -->
    <bean id="methodCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">  
        <property name="cacheManager">  
            <ref local="cacheManager"/>  
        </property>  
        <property name="cacheName">  
            <value>com.easyway.MethodCache</value>  
        </property>  
    </bean>  
    
    <!-- 自定义缓存拦截器 -->
    <bean id="methodCacheInterceptor" class="com.easyway.ecache.service.MethodCacheInterceptor">  
        <property name="cache">  
            <ref local="methodCache"/>  
        </property>  
    </bean>  
    
    <!-- 自定义拦截器 -->
    <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  
        <property name="advice">  
            <ref local="methodCacheInterceptor"/>  
        </property>  
        <!-- 下面的配置就使得在数据访问时,cache将拦截从数据库获取的数据,与cache数据比较,如有就不放入cache,没有就放入,更新到数据库去,也是先存入cache,再更新到数据库中去 -->  
        <property name="patterns">  
            <list>  
                <value>.*getServiceName</value> 
                <value>.*testMethod</value>  
            </list>  
        </property>  
    </bean>  
    <!-- 声明一个服务 -->
    
    <bean id = "ticketServiceTarget"  class="com.easyway.ecache.service.TicketService" />  
    
    <!-- 相关的服务 -->
     <bean id="ticketService"
       class="org.springframework.aop.framework.ProxyFactoryBean">
       <property name="target">  
            <ref local="ticketServiceTarget"/>  
        </property>  
        <property name="interceptorNames">  
            <list>  
                <value>methodCachePointCut</value>  
            </list>  
        </property>  
     </bean>
     
</beans>  

 

4.测试服务类:

Java代码 复制代码 收藏代码
  1. package com.easyway.ecache.service;   
  2.   
  3. import java.util.List;   
  4. /**  
  5.  * 对其所有的以testMethod* ,getServiceName方式命令的方法,  
  6.  * 进行缓存处理。当调用其他命令时,不进行缓存  
  7.  * @author longgangbai  
  8.  *  
  9.  */  
  10. @SuppressWarnings("unchecked")   
  11. public class TicketService {   
  12.        
  13.     public String testMethod(){      
  14.         System.out.println("没走缓存,直接调用TestService.testMethod()");      
  15.         return "china";      
  16.     }      
  17.           
  18.     public void updateMethod(){      
  19.         System.out.println("updateMethod");      
  20.     }      
  21.           
  22.     public void insertMethod(){      
  23.         System.out.println("insertMethod");      
  24.     }      
  25.           
  26.     public void deleteMethod(){      
  27.         System.out.println("deleteMethod");      
  28.     }         
  29.   
  30.     /**  
  31.      * 需要缓存的集合  
  32.      */  
  33.     private List ticketList;   
  34.     /**  
  35.      * 需要缓存的服务名称  
  36.      */  
  37.     private String serviceName;   
  38.   
  39.     public String getServiceName() {   
  40.         return serviceName;   
  41.     }   
  42.   
  43.     public void setServiceName(String serviceName) {   
  44.         this.serviceName = serviceName;   
  45.     }   
  46.   
  47.     public List getTicketList() {   
  48.         return ticketList;   
  49.     }   
  50.     public void setTicketList(List ticketList) {   
  51.         this.ticketList = ticketList;   
  52.     }   
  53.     /**  
  54.      * 修改的服务端名称备注但是不缓存  
  55.      * @param serviceName  
  56.      */  
  57.     public void changesetServiceName(String serviceName) {   
  58.         this.serviceName = serviceName;   
  59.     }   
  60. }  
package com.easyway.ecache.service;

import java.util.List;
/**
 * 对其所有的以testMethod* ,getServiceName方式命令的方法,
 * 进行缓存处理。当调用其他命令时,不进行缓存
 * @author longgangbai
 *
 */
@SuppressWarnings("unchecked")
public class TicketService {
	
	public String testMethod(){   
        System.out.println("没走缓存,直接调用TestService.testMethod()");   
        return "china";   
    }   
       
    public void updateMethod(){   
        System.out.println("updateMethod");   
    }   
       
    public void insertMethod(){   
        System.out.println("insertMethod");   
    }   
       
    public void deleteMethod(){   
        System.out.println("deleteMethod");   
    }      

	/**
	 * 需要缓存的集合
	 */
	private List ticketList;
	/**
	 * 需要缓存的服务名称
	 */
	private String serviceName;

	public String getServiceName() {
		return serviceName;
	}

	public void setServiceName(String serviceName) {
		this.serviceName = serviceName;
	}

	public List getTicketList() {
		return ticketList;
	}
	public void setTicketList(List ticketList) {
		this.ticketList = ticketList;
	}
	/**
	 * 修改的服务端名称备注但是不缓存
	 * @param serviceName
	 */
	public void changesetServiceName(String serviceName) {
		this.serviceName = serviceName;
	}
}

 

5.测试用例

Java代码 复制代码 收藏代码
  1. package com.easyway.ecache.service;   
  2.   
  3. import org.springframework.context.ApplicationContext;   
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;   
  5.      
  6. /**    
  7.  * 这里使用了ehcache与spring结合,这里并没用用到数据库,用spring只是用来管理bean,  
  8.  * 这里用ehcache就相当于数据库,存放对象信息    
  9.  *  @author longgangbai  
  10.  */     
  11.      
  12. @SuppressWarnings({"unchecked"})      
  13. public class HelloEhcacheSpring{      
  14.     public static void main(String[] args) {      
  15.         ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");      
  16.               
  17.         TicketService ticketSrv = (TicketService) context.getBean("ticketService");   
  18.            
  19.         //配置了spring就可以从配置文件里找到对应的接口实现类,再生成实例对象,以完成业务处理      
  20.         String srvName0=ticketSrv.testMethod();   
  21.            
  22.         //获取初始化服务端名称   
  23.         System.out.println("srvName0="+srvName0);   
  24.            
  25.         //设置存储的名称   
  26.         ticketSrv.setServiceName("ticketService");   
  27.            
  28.         String srvName1=ticketSrv.testMethod();   
  29.            
  30.         //获取服务端名称   
  31.         System.out.println("srvName1="+srvName1);   
  32.            
  33.         //修改服务名称但是不缓存   
  34.         ticketSrv.updateMethod();   
  35.            
  36.         String srvName2=ticketSrv.testMethod();   
  37.            
  38.         //获取服务端名称来源自缓存注意观察   
  39.         System.out.println("srvName2="+srvName2);   
  40.           
  41.           
  42.     }      
  43.        
  44. }    
package com.easyway.ecache.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
  
/**  
 * 这里使用了ehcache与spring结合,这里并没用用到数据库,用spring只是用来管理bean,
 * 这里用ehcache就相当于数据库,存放对象信息  
 *  @author longgangbai
 */  
  
@SuppressWarnings({"unchecked"})   
public class HelloEhcacheSpring{   
    public static void main(String[] args) {   
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");   
           
        TicketService ticketSrv = (TicketService) context.getBean("ticketService");
        
        //配置了spring就可以从配置文件里找到对应的接口实现类,再生成实例对象,以完成业务处理   
    	String srvName0=ticketSrv.testMethod();
    	
    	//获取初始化服务端名称
    	System.out.println("srvName0="+srvName0);
    	
    	//设置存储的名称
    	ticketSrv.setServiceName("ticketService");
    	
    	String srvName1=ticketSrv.testMethod();
    	
    	//获取服务端名称
    	System.out.println("srvName1="+srvName1);
    	
    	//修改服务名称但是不缓存
    	ticketSrv.updateMethod();
    	
    	String srvName2=ticketSrv.testMethod();
    	
    	//获取服务端名称来源自缓存注意观察
        System.out.println("srvName2="+srvName2);
       
       
    }   
    
}  

 

6.测试结果:

没走缓存,直接调用TestService.testMethod()

打印信息如下:
set into cache
out cache
srvName0=china
out cache
srvName1=china
updateMethod
out cache
srvName2=china

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics