Add Google's Guava cache (demo) in spring

Source: Internet
Author: User

Configuration in 1.pom files

    <Dependencies>        <Dependency>            <groupId>Org.springframework</groupId>            <Artifactid>Spring-context-support</Artifactid>            <version>4.2.4.RELEASE</version>        </Dependency>        <Dependency>            <groupId>Org.springframework</groupId>            <Artifactid>Spring-beans</Artifactid>            <version>4.2.4.RELEASE</version>        </Dependency>        <Dependency>            <groupId>Com.google.guava</groupId>            <Artifactid>Guava</Artifactid>            <version>19.0</version>        </Dependency>        <Dependency>            <groupId>Junit</groupId>            <Artifactid>Junit</Artifactid>            <version>4.12</version>        </Dependency>        <Dependency>            <groupId>Org.projectlombok</groupId>            <Artifactid>Lombok</Artifactid>            <version>1.16.20</version>        </Dependency>    </Dependencies>

2.GuavaCacheManagerConfig Configuration Class

 PackageCom.zy;ImportCom.google.common.cache.CacheBuilder;ImportCom.google.common.collect.Maps;ImportOrg.springframework.cache.Cache;ImportOrg.springframework.cache.guava.GuavaCache;ImportOrg.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;Importjava.util.Collection;ImportJava.util.Map;ImportJava.util.concurrent.ConcurrentMap; Public classGuavacachemanagerconfigextendsAbstracttransactionsupportingcachemanager {Private Finalconcurrentmap<string, cache> cachemap =Maps.newconcurrentmap (); Privatemap<string, cachebuilder> buildermap =Maps.newhashmap (); @Overrideprotectedcollection<?extendsCache>loadcaches () {returncachemap.values (); }    //get a sample of a cache@Override PublicCache GetCache (String name) {Cache Cache= This. Cachemap.get (name); if(NULL==cache) {            synchronized( This. Cachemap) {Cache= This. Cachemap.get (name); if(NULL= = Cache && This. Buildermap.containskey (name)) {Cachebuilder Builder= This. Buildermap.get (name); Cache=Createguavacache (name, builder);  This. Cachemap.put (name, cache); }            }        }        returnCache; }    PrivateCache Createguavacache (String name, Cachebuilder builder) {Com.google.common.cache.Cache<object, object>Cache; if(Builder = =NULL) {Cache=Cachebuilder.newbuilder (). build (); }Else{Cache=Builder.build (); }        return NewGuavacache (name, Cache, Isallownullvalues ()); }    Private Booleanisallownullvalues () {return true; }    //Multi-group cache pool injection in configuration     Public voidSetconfigmap (map<string, cachebuilder>Configmap) {         This. Buildermap =Configmap; }}

3.applicationcontext-cache-guava.xml 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:cache= "Http://www.springframework.org/schema/cache"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp//Www.springframework.org/schema/cachehttp//www.springframework.org/schema/cache/spring-cache.xsd "><!--1. Register the class that needs to join the cache in-<bean id= "Guavaservice"class= "Com.zy.GuavaServiceImpl"/> <!--==========================2. Open Guava Cache start ====================-<!-- Declaring cache annotations on--<cache:annotation-driven cache-manager= "CacheManager" proxy-target-class= "true"/> <!--declaration using spring to manage cache groups--<bean id= "CacheManager"class= "Org.springframework.cache.support.CompositeCacheManager" > <property name= "cachemanagers" > &lt ;list> <ref bean= "Guavacachemanager"/> </list> </property> &L T;property name= "Fallbacktonoopcache" value= "true"/> </bean> <!--the creation of a cache-specific implementation class to inject class into custom classes and &L T;bean id= "Guavacachemanager"class= "Com.zy.GuavaCacheManagerConfig" > <!--Here you can configure a set of cache pools to correspond to different business types a default cache of "Guava" is implemented and built-in <propert Y name= "Configmap" > <map key-type= "java.lang.String" value-type= "Com.google.common.cache.CacheBuilder"                ;            <!--the cache is equal to value on the annotation on the service layer implementation class--<entry key= "Guava" value-ref= "Defaultcachebuilder"/> </map> </property> </bean> <!--here to directly build the "guava" default Cache--<bean id= "DEFAULTCA Chebuilder "class= "Com.google.common.cache.CacheBuilder"Factory-method= "from" > <!--cache pool Size time (timed recycle cache entries are not ' write '-accessed for a given amount of time and Refreshafterwrite expireafteraccess available) Of course there are other optional Components (Weakkeys,removallistener and so on!)--<constructor-arg value= "maximumsize=10000, expireafteraccess=5s"/ > </bean> <!--==========================2. Turn on guava cache end ====================--></beans>

4.GuavaDTO

 Package Com.zy; Import Lombok. Allargsconstructor; Import Lombok. Builder; Import Lombok. Data; Import Lombok. Noargsconstructor, @Data @noargsconstructor@allargsconstructor@builderpublicclass guavadto {    private  Integer ID;     Private String name;}

Implementation class of 5.GuavaServiceImpl

 PackageCom.zy;Importorg.springframework.cache.annotation.Cacheable; Public classGuavaserviceimpl {//Spring EL//guavadto Common DTO//@Cacheable (value = "Guava", key = "' Testguavacache: ' + #guavaDTO. ID + #guavaDTO. Name")     //value is the name of the cache pool in the profile key is the key name@Cacheable (value = "Guava", key = "' Testguavacache: ' + #guavaDTO. ID + #guavaDTO. Name")     Public voidTestguavacache (guavadto guavadto) {System.out.println ("No in ======= cache, enter method to query ========="); }}

If the service implementation class is a Delete method, then on the method, add the @cacheevict annotation

If the service implementation class is an update method, then on the method, add the @cacheput annotation (each execution, will enter the method)

6. Test class Guavatest

 PackageCom.zy;Importorg.junit.Test;ImportOrg.springframework.context.support.ClassPathXmlApplicationContext; Public classguavatest {@Test Public voidFN ()throwsinterruptedexception {classpathxmlapplicationcontext ApplicationContext=NewClasspathxmlapplicationcontext ("Applicationcontext-cache-guava.xml"); Guavaserviceimpl Guavaservice= (Guavaserviceimpl) applicationcontext.getbean ("Guavaservice"); System.out.println ("1th visit: No. 1th tom=========================="); Guavaservice.testguavacache (NewGuavadto (1, "Tom")); System.out.println ("2nd visit: No. 1th tom=========================="); Guavaservice.testguavacache (NewGuavadto (1, "Tom")); Guavaservice.testguavacache (NewGuavadto (1, "Tom")); System.out.println ("1th visit: No. 2nd jerry=========================="); Guavaservice.testguavacache (NewGuavadto (2, "Jerry")); Thread.Sleep (5000); /*** The expiration time in the configuration file is 5000ms **/System.out.println ("3rd visit: No. 1th tom=========================="); Guavaservice.testguavacache (NewGuavadto (1, "Tom")); }}

7. The test results are as follows:

Add Google's Guava cache (demo) in spring

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.