Spring + Ehcache Integration

Source: Internet
Author: User

A: Ehcache introduction

EhCache is a pure Java in-process caching framework, which is fast and capable, and is the default Cacheprovider in Hibernate.
Similar to making a backup of the database, be sure to note the data dirty read when using Ehcache

Second: The knowledge points that spring needs
1 Spring AOP application several ways: Proxyfactorybean dynamic agent, 2.0 version before;<aop> label 2.0 version
2 Spring Get access point information: Joinpoint and Proceedingjoinpoint (limited to surround notification use)

Three: Use

1 Ehcache configuration:

<?xml version= "1.0" encoding= "UTF-8"?>    <ehcache>      <diskstore path= "C:\\myapp\\cache"/>      <defaultcache          maxelementsinmemory= "1"          eternal= "false"           Timetoidleseconds= "          timetoliveseconds" = "          overflowtodisk" = "true"          />    <cache name= "System_cache"          maxelementsinmemory= "One"          eternal= " False "          timetoidleseconds=" 300000 "          timetoliveseconds=" 600000 "           Overflowtodisk= "true"          />  </ehcache>                    

2 Spring configuration file:

<?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:p= "http://www.springframework.org/schema/p"Xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:context= "Http://www.springframework.org/schema/context"XMLNS:AOP= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:jee= "Http://www.springframework.org/schema/jee"Xmlns:util= "Http://www.springframework.org/schema/util" xmlns:lang= "Http://www.springframework.org/schema/lang"XMLNS:JMS= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMS" xmlns:security= "http://www.springframework.org/schema/security"Xmlns:dwr= "Http://www.directwebremoting.org/schema/spring-dwr"Xmlns:jdbc= "Http://www.springframework.org/schema/jdbc"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http//Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp//Www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-3.0.xsdhttp//Www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-3.0.xsdhttp//Www.springframework.org/schema/utilhttp://www.springframework.org/schema/util/spring-util-3.0.xsdhttp//Www.springframework.org/schema/langhttp://www.springframework.org/schema/lang/spring-lang-3.0.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/JMShttp://www.springframework.org/schema/jms/spring-jms-3.0.xsdhttp//www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-3.0.xsdhttp//Www.directwebremoting.org/schema/spring-dwrhttp://www.directwebremoting.org/schema/spring-dwr-2.0.xsdhttp//Www.springframework.org/schema/jdbchttp://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"><!--activate annotation function--<context:annotation-config/> <!--on using @transactional annotations--<tx:an Notation-driven transaction-manager= "TransactionManager"Proxy-target-class= "true"/> <context:component-scan base- Package= "Ehcache.*"scoped-proxy= "Targetclass" > </context:component-scan> <!--DataSource--<bean id= "DataSource"class= "Com.mchange.v2.c3p0.ComboPooledDataSource"Destroy-method= "Close" > <property name= "driverclass" value= "Oracle.jdbc.driver.OracleDriver"/> <proper         Ty name= "Jdbcurl" value= "Jdbc:oracle:thin: @localhost: 1521/orcl"/> <property name= "user" value= "Oracle"/> <property name= "Password" value= "Oracle"/> <!--connection pool other configurations--<property name= "Minpools Ize "value=" 2 "/> <property name=" maxpoolsize "value=" 5 "/> <property name=" MaxIdleTime "value=" "/> <property name=" acquireincrement "value=" 3 "/> <property name=" maxstatements "value=" 10 " /> <property name= "initialpoolsize" value= "2"/> <property name= "Idleconnectiontestperiod" value = "/>" <property name= "Numhelperthreads" value= "ten"/> </bean> <bean id= "JdbcTemplate"class= "Org.springframework.jdbc.core.JdbcTemplate" > <property name= "dataSource" ref= "DataSource" ></ property> </bean> <bean id= "Cachedao"class= "Ehcache.integration.dao.CacheDao" > <property name= "jdbctemplate" ref= "JdbcTemplate"/> </bean> <bean id= "Cacheservice"class= "Ehcache.integration.service.CacheService" > <property name= "Cachedao" ref= "Cachedao"/> </bean> <!--reference Ehcache configuration--<bean id= "Defaultcachemanager"class= "Org.springframework.cache.ehcache.EhCacheManagerFactoryBean" > <property name= "configlocation" > <value>WebContent/resource/ehcache.xml</value> </property> </bean> <!--definition Ehcach E factory and set the cache name---<bean id= "EhCache" usedclass= "Org.springframework.cache.ehcache.EhCacheFactoryBean" > <property name= "CacheManager" > <ref Local= "Defaultcachemanager"/> </property> <property name= "CacheName" > <value& Gt System_cache</value> </property> </bean> <!--facets--<bean id= "Aspectclass"class= "Ehcache.integration.interceptor.MethodCacheInterceptor" > <property name= "Cache" > <ref loca L= "EhCache"/> </property> </bean> <aop:config proxy-target-class= "true" > <aop:aspect ref= "Aspectclass" > <aop:pointcut expression= "Execution (* ehcache.integratio n.service.*service.* (..)) " Id= "Servicepointcut"/> <aop:around method= "dointercept" pointcut-ref= "Servicepointcut"/> </aop:a Spect> </aop:config></beans>

3 facets and notification method definitions:

  

 PackageEhcache.integration.interceptor;Importjava.io.Serializable;ImportNet.sf.ehcache.Cache;Importnet.sf.ehcache.Element;ImportOrg.aspectj.lang.ProceedingJoinPoint; Public classMethodcacheinterceptor {Privatecache Cache;  Public voidSetcache (Cache cache) { This. cache =Cache; }    /*** Intercept the Service/dao method and find out if the result exists, return the value in the cache if it exists, * Otherwise, return the database query result and put the query result in cache * 1) Joinpoint * java.lang.object[] Getargs (): Gets the parameter list of the connection point method runtime; * Signature getsignature (): Gets the method signature object of the connection point; * java. Lang.     Object Gettarget (): Gets the target object where the connection point is located; * Java.lang.Object getthis (): Gets the proxy object itself; * 2) Proceedingjoinpoint (only for surround notification) * Proceedingjoinpoint inherits the Joinpoint Subinterface, which adds two methods for executing the connection point method: * Java.lang.Object Proceed () throws Java.lang.Throwable: by reflection     Executes the method at the connection point of the target object; * Java.lang.Object proceed (java.lang.object[] args) throws Java.lang.Throwable: Perform the method at the target object connection point by reflection * @throwsThrowable*/     PublicObject dointercept (Proceedingjoinpoint joinpoint)throwsthrowable {String targetName=joinpoint.gettarget (). GetClass (). GetName (); String MethodName=joinpoint.getsignature (). GetName (); object[] Arguments=Joinpoint.getargs (); String CacheKey=Getcachekey (TargetName, methodName, arguments); Element element=Cache.get (CacheKey); Object result=NULL; if(element = =NULL) {result=joinpoint.proceed (); Element=NewElement (CacheKey, (Serializable) result);          Cache.put (Element); }        returnElement.getvalue (); }    /*** method to obtain the cache key, the cache key is the unique identifier of an element in the cache * Cache key includes package name + class name + method name, such as Com.co.cache.service.UserServiceIm Pl.getalluser*/    Privatestring Getcachekey (String targetName, String methodName, object[] arguments) {stringbuffer sb=NewStringBuffer (); Sb.append (TargetName). Append ("."). Append (MethodName); if((Arguments! =NULL) && (Arguments.length! = 0)) {             for(inti = 0; i < arguments.length; i++) {sb.append ("."). Append (Arguments[i]); }        }        returnsb.tostring (); }}

4 System Sevice Method:

 PackageEhcache.integration.service;Importjava.util.List;ImportSpring.tx.bean.TxdemoBean;ImportEhcache.integration.dao.CacheDao;/*** Class Description: Service Layer *@authorShiro *@version1.0 createdate:2015-2-2 * * @history: * @updateDate @updatePerson @declare **/ Public classCacheservice {PrivateCachedao Cachedao; /*** Method Description: **/     PublicList<txdemobean>getList () {List<TxdemoBean> rows =cachedao.selectlist (); returnrows; }    /**     * @returnThe Cachedao*/     PublicCachedao Getcachedao () {returnCachedao; }    /**     * @paramCachedao the Cachedao to set*/     Public voidSetcachedao (Cachedao Cachedao) { This. Cachedao =Cachedao; }}

5 Call Entry:

 Packageehcache.integration;Importjava.util.List;ImportOrg.springframework.context.ApplicationContext;ImportOrg.springframework.context.support.FileSystemXmlApplicationContext;ImportSpring.tx.bean.TxdemoBean;ImportEhcache.integration.service.CacheService;/*** Class Description: Ehcache integrated Spring *@authorShiro *@version1.0 createdate:2015-4-20 * * @updateDate * @updatePerson * @declare*/ Public classAcce { Public Static voidMain (string[] args) {ApplicationContext context=NewFilesystemxmlapplicationcontext ("Webcontent/resource/applicationcontext-ehcache.xml"); Cacheservice Cacheservice= (Cacheservice) context.getbean ("Cacheservice");//CacheManager CacheManager = (CacheManager) context.getbean ("CacheManager");////Cache Levelonecache = Cachemanager.getcache ("Syscache");         for(inti = 0; I < 5; i++) {List<TxdemoBean> rows =cacheservice.getlist ();  for(Txdemobean txdemobean:rows) {System.out.println (txdemobean.tostring ()); }        }    }}

Spring + ehcache Consolidation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.