Spring 에서 AOP 가 EHcache 통합 실현(1)

프로젝트 에 캐 시 를 사용 합 니 다.저 는 OSCache 입 니 다.오늘 시간 이 있 으 면 모든 EHcache 캐 시 애플 리 케 이 션 을 주목 하 십시오.우선 Spring 과 EHcache 가 AOP 로 구현 한 캐 시 를 살 펴 보 자.
 
1.우선 EHcache 를 사용 하여 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 방법 차단 기 를 작성 합 니 다.이 곳 은 서 라운드 알림 방식 으로 차단 합 니 다.
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 의 캐 시 설정 과 유사 한 것 에 대한 설정:
<?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.테스트 서비스 클래스:
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.테스트 용례
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.test Method()를 직접 호출 합 니 다.
인쇄 정 보 는 다음 과 같 습 니 다:set into cacheout cachesrvName 0=chinaout cachesrvName 1=chinaupdateMethodout cachesrvName 2=china

좋은 웹페이지 즐겨찾기