Cache initial Solution (iii)---Spring3.0 annotation-based cache configuration +ehcache and Oscache

Source: Internet
Author: User

This article builds a generic project to illustrate how the spring annotation cache is used, and about how to use the annotation cache in Web applications, see:

Spring annotation-based cache configuration--web Application Example

I. INTRODUCTION
Support for many third-party caching scenarios is available in spring's modules package, including:
EHCache
Oscache (Opensymphony)
Jcs
Gigaspaces
JBoss Cache
Wait a minute.
Configuring these third-party caching scenarios in spring is simple, with many introductions on the web, focusing only on how to configure the annotation-based cache configuration.
This article will illustrate in detail how to use spring to configure the annotation-based cache configuration by example Ehcache and Oscache, and note that the cache here is method-level.

Two. Reliance
Let's introduce the jar dependencies of Ehcache and Oscache before starting to describe how to do the cache configuration.
EHCache:
Ehcache-core-1.7.2.jar
Jakarta-oro-2.0.8.jar
Slf4j-api-1.5.8.jar
Slf4j-jdk14-1.5.8.jar

Oscache:
Oscache-2.4.1.jar

In addition, the jars required for both are as follows:
Cglib-nodep-2.1_3.jar
Commons-logging.jar
Log4j-1.2.15.jar
Spring-modules-cache.jar
Spring.jar

Three. Configuration

Both caches can be configured in the spring configuration file, one of which is spring2.0 's previously fully bean-based configuration, and one that uses the subsequent namespace-based simple configuration, with the same two configuration effects, each of which is described below:


EHCache:
1) General Configuration

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:   Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "><!--AOP Proxy, this is a must, otherwise the cache does not work--><bean id= "Autoproxy" class= "Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/><!-- The EhCache management factory is used to specify the EhCache profile path--><bean id= "CacheManager" class= " Org.springframework.cache.ehcache.EhCacheManagerFactoryBean "><property name=" configlocation "value=" Classpath:ehcache.xml "/></bean><bean id=" Cacheproviderfacade "class=" Org.springmodules.cache.provider.ehcache.EhCacheFacade "><property name=" CacheManager "ref=" CacheManager "/ ></bean><!--1.5+ Annotation to find cached business methods based on annotations--><bean id= "Cachingattributesource" class= " Org.springmodules.cache.annotations.AnnotationCachingAttributeSource "></bean><!--Cache Blocker: Defines the cache module, Ehcache only need to specify the cache name in the configuration file--><bean id= "Cachinginterceptor" class= " Org.springmodules.cache.interceptor.caching.MetadataCachingInterceptor "><property name=" Cacheproviderfacade "ref=" Cacheproviderfacade "/><property name=" Cachingattributesource "ref=" Cachingattributesource "/><property name=" cachingmodels "><props><prop key=" testCaching "> cachename=testcache</prop></props></property></bean><!--An AOP notifier that looks up cache business methods based on annotations-- <bean id= "Cachingattributesourceadvisor" class= " Org.springmodules.cache.interceptor.caching.CachingAttributeSourceAdvisor "><constructor-arg ref=" Cachinginterceptor "/></bean><!--business method for triggering cache refresh actions based on annotations--><bean id=" Flushingattributesource "class = "Org.springmodules.cache.annotations.AnnotationFlushingAttributeSource" ></bean><!--Flush Interceptor: Defines the refresh policy, Based on that module ID, refresh the corresponding cache--> <bean id= "Flushinginterceptor" class= " Org.springmodules.cache.interceptor.flush.MetAdataflushinginterceptor "><property name=" Cacheproviderfacade "ref=" Cacheproviderfacade "/><property Name= "Flushingattributesource" ref= "Flushingattributesource"/><property name= "FlushingModels" ><map ><entry key= "testflushing" ><beanclass= " Org.springmodules.cache.provider.ehcache.EhCacheFlushingModel "><property name=" Cachenames "><list ><value>testCache</value></list></property> <!--error, should not be directly set CacheName <property Name= "CacheName" value= "Testcache"/>--></bean></entry></map></property></bean ><!--an AOP notifier--><bean id= "Flushingattributesourceadvisor" class= "that refreshes the cached business method based on the annotation lookup Org.springmodules.cache.interceptor.flush.FlushingAttributeSourceAdvisor "><constructor-arg ref=" Flushinginterceptor "/></bean><!--test object--><bean id=" Testcache "class=" com. Testcache "/></beans>

2) Namespace Configuration

<?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:ehcache= "Http://www.springmodules.org/schema/ehcache" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsdhttp://www.springmodules.org/schema/ehcache http://www.springmodules.org/schema/cache/ Springmodules-ehcache.xsd "><!--Here you do not need to configure this <bean id=" Autoproxy "class=" Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator "/>--><ehcache:config configlocation= "Classpath:ehcache.xml" id= "Cacheprovider"/><ehcache:annotations providerid= "Cacheprovider" ><ehcache:caching cachename= "Testcache" id= "testcaching"/><ehcache:flushing cacheNames= "TestCache" id= "Testflushing"/></ehcache:annotations><bean id= "testcache" class= "com. Testcache "/></beans>

 oscache:
1) Normal configuration

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:   Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd "><!--This is a must, otherwise the cache does not work--><bean id=" Autoproxy "class=" Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator "/><!-- Cache Management Factory: Use Oscache cache management to configure the configuration file path used by Oscache--><bean id= "CacheManager" class= " Org.springmodules.cache.provider.oscache.OsCacheManagerFactoryBean "><property name=" Configlocation "value= "Classpath:oscache.properties"/></bean><!--cache provides: Oscache--><bean id= "Cacheproviderfacade" class = "Org.springmodules.cache.provider.oscache.OsCacheFacade" ><property name= "CacheManager" ref= "CacheManager" /></bean><!--1.5+ Annotation to find cached business methods based on annotations--><bean id= "Cachingattributesource" class= " Org.springmodules.cache.annotations.Annotationcachingattributesource "></bean><!--cache blocker: Defines the cache module, and the corresponding refresh policy, and the cache belongs to the group--> <bean Id= "Cachinginterceptor" class= "Org.springmodules.cache.interceptor.caching.MetadataCachingInterceptor" >< Property Name= "Cacheproviderfacade" ref= "Cacheproviderfacade"/><property name= "Cachingattributesource" ref= " Cachingattributesource "/><property name=" cachingmodels "><props><prop key=" testCaching "> Refreshperiod=86400;cronexpression=0 1 * * *;groups=pb_test</prop></props></property></bean ><!--AOP notifier--><bean id= "Cachingattributesourceadvisor" class= "for the annotation-based lookup caching business method Org.springmodules.cache.interceptor.caching.CachingAttributeSourceAdvisor "><constructor-arg ref=" Cachinginterceptor "/></bean><!--business method for triggering cache refresh actions based on annotations--><bean id=" Flushingattributesource "class = "Org.springmodules.cache.annotations.AnnotationFlushingAttributeSource" ></bean><!--Flush Interceptor: Defines the refresh policy, Refresh the corresponding cache group based on that module ID--&GT;&LT;bean id= "Flushinginterceptor" class= "Org.springmodules.cache.interceptor.flush.MetadataFlushingInterceptor" ><property name= "Cacheproviderfacade" ref= "Cacheproviderfacade"/><property name= " Flushingattributesource "ref=" Flushingattributesource "/><property name=" Flushingmodels "><props> <prop key= "testflushing" >groups=pb_test</prop></props></property></bean><!-- The AOP notifier--><bean id= "Flushingattributesourceadvisor" class= "that refreshes the cached business method based on the annotation lookup Org.springmodules.cache.interceptor.flush.FlushingAttributeSourceAdvisor "><constructor-arg ref=" Flushinginterceptor "/></bean><bean id=" testcache "class=" com. Testcache "/></beans>

 
2) namespace configuration

<?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:oscache= "Http://www.springmodules.org/schema/oscache" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-2.5.xsdhttp://www.springmodules.org/schema/oscache http://www.springmodules.org/schema/cache/ Springmodules-oscache.xsd "><!--Here you do not need to configure this <bean id=" Autoproxy "class=" Org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator "/>--><oscache:config configlocation= "Classpath:oscache.properties" id= "Cacheprovider"/><oscache:annotations providerid= " Cacheprovider "><oscache:caching id=" testcaching "groups=" pb_test "cronexpression=" 0 1 * * * "refreshPeriod=" 86400 "/><oscache:flushing id=" testflushing "groups=" pb_test "/></oscache:annotations><bean id=" Testcache "class=" com. Testcache "/></beans> 

Four. Annotations

@Cacheable: Declares that the return value of a method should be cached

Example: @Cacheable (modelid = "testcaching")

@CacheFlush: Declaring one method is to empty the cached trigger

Example: @CacheFlush (modelid = "testcaching")

Five. Testing

This is done by using a class with a main function to test the code as follows:

/** COPYRIGHT Beijing Netqin-tech Co.,ltd.   Source file name: Testcache.java * Function: (description file function) * Version: @version 1.0 * Date of Establishment: 2010-2-24 * Description: (description of the use of the text    Conditions) * Revision history: (Main Historical change reason and explanation) * yyyy-mm-dd | Author |  Change Description * 2010-2-24 |  Hanqunfeng | Created */package com;import Net.sf.ehcache.cachemanager;import org.springframework.context.ApplicationContext; Import Org.springframework.context.support.classpathxmlapplicationcontext;import Org.springmodules.cache.annotations.cacheflush;import Org.springmodules.cache.annotations.cacheable;import                                                           Com.opensymphony.oscache.general.generalcacheadministrator;public class Testcache {/** * Description: < describes function implementation function;.                            <br> *<p>                                                                                                                          * @param args */static String context = null;static Applica Tioncontext applicationcontext;static{context = "Applicationcontext-ehcache.xml";//ehcache simple Configuration (namespace)//context = " Applicationcontext-ehcache_full.xml ";//ehcache full configuration//context =" Applicationcontext-oscache.xml ";// Oscache Simple Configuration (namespace)//context = "Applicationcontext-oscache_full.xml";//oscache full configuration ApplicationContext = new Classpathxmlapplicationcontext (context);}    public static void Main (string[] args) {Testcache test = (Testcache) applicationcontext.getbean ("Testcache");    System.out.println (test.getname (0));    System.out.println (test.getname (0));    System.out.println (test.getname (0)); Test.flush ();//test.   Osflushall ();// Test.    Ehflushall ();    System.out.println (test.getname (0));    System.out.println (test.getname (0));    System.out.println (test.getname (0)); } @Cacheable (modelid = "testcaching") public String getName (int i) {System.out.println ("Processing testcaching"); return "Nihao:" +i;} @CacheFlush (modelid = "testflushing") public void Flush () {System.out.println ("Processing testflushing");} /** * Description: <oscache refresh all cache;.                                                                                                                                                    <br>*<p> problem: Flushall () no longer caches data */public void Osflushall () {Generalcacheadministrator cacheadmin = (generalcacheadministrator) applicationContext.g Etbean ("CacheManager"); Cacheadmin.flushall ();SYSTEM.OUT.PRINTLN ("Processing Osflushingall");} /** * Description: < empty cache of the specified group name;.                                                                                                                                                                                                                                <br>*<p>                                                                                       * @param groupName */public void Osflushgroup (String groupName) {generalcacheadministrator cacheadmin = (generalcacheadministrator) appli Cationcontext.getbean ("CacheManager"); Cacheadmin.flushgroup (groupName);//clear the cache for this group: PB_TESTSYSTEM.OUT.PRINTLN (" Processing Osflushinggroup: "+groupname);} /** * Description: <ehcache refresh all cache;.                                                        <br>*<p> success                                                                                                                          */public void Ehflushall () {Cachemanag Er cacheadmin = (cachemanager) applicationcontext.getbean ("CacheManager"); Cacheadmin.clearall (); SYSTEM.OUT.PRINTLN ("Processing Ehflushingall");} /** * Description: < empty cache of the specified name;.                                                                                                                                                                                                                                <br>*<p>                                                                                       * @param cachename */public void Ehflushcache (String cachename) {CacheManager cacheadmin = (CacheManager) applicationcontext.getbean ("CAC Hemanager "); Cacheadmin.getcache (CachenAME). Flush ();//Clear a single cache: testCacheSystem.out.println ("Processing ehflushingcachename:" +cachename);}} 

Test results

Processing testcaching
nihao:0
nihao:0
nihao:0
Processing testflushing
Processing testcaching
nihao:0
nihao:0
nihao:0

Six. Cache configuration Files

Ehcache.xml

<?xml version= "1.0" encoding= "UTF-8"? ><ehcache xmlns:xsi= "http:// Www.w3.org/2001/XMLSchema-instance "xsi:nonamespaceschemalocation=" Ehcache.xsd "updatecheck=" true "monitoring="            AutoDetect "><diskstore path=" Java.io.tmpdir "/> <defaultcache maxelementsinmemory=" 10000 "             Eternal= "false" timetoidleseconds= "timetoliveseconds=" overflowtodisk= "true" maxelementsondisk= "10000000" diskpersistent= "false" diskexpirythreadintervalseconds= "120 "memorystoreevictionpolicy=" LRU "/> <cache name=" Testcache "maxelementsinmemory=" 10 "Maxelementsondisk=" "eternal=" false "overflowtodisk=" true "Diskspoolbuffe             rsizemb= "timetoidleseconds=" timetoliveseconds= "memorystoreevictionpolicy=" LFU " /></ehcache> 

Oscache.properties

      1. cache.capacity=

Cache initial Solution (iii)---Spring3.0 annotation-based cache configuration +ehcache and Oscache

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.