Springboot+mybatis+redis implementing Level Two caching

Source: Internet
Author: User
Tags aop

For the query more projects can be considered to configure level two cache, MyBatis itself, the level two cache is cached locally, but for multiple nodes of the project, there may be data inconsistencies, so the use of Redis cache, so that the level two cache data can be cached to memory, Enables data synchronization for multiple node projects.

1. Configuring Redis Connections

#redisgmall. Redis.host=172.16.1.250gmall.redis.port=6379gmall.redis.pass=  Gworld2017gmall.redis.photo.database=6#最大分配的对象数  gmall.redis.maxActive=12000# Maximum number of objects that can hold the Idel state gmall.redis.maxIdle=600#当池内没有返回对象时, maximum wait time  gmall.redis.maxWait=2000  Gmall.redis.timeout=5000#当调用borrow The object method, check for validity  gmall.redis.testOnBorrow=true Gmall.redis.testOnReturn =true    If validation check is performed #当调用return the object method Gmall.redis.minIdle=5
<?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" xmlns:task= "Http://www.springframework.org/schema/task"xsi:schemalocation="http//Www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp//WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOPhttp://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp//Www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp//Www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-3.0.xsd"    default-lazy-init= "false" > <bean id= "jedisconnfactory"class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory"Primary= "true" > <property name= "hostName" value= "${gmall.redis.host}"/> <property name= "Port" value= "$ {gmall.redis.port} "/> <property name=" password "value=" ${gmall.redis.pass} "/> <property name=" Timeout "value=" ${gmall.redis.timeout} "/> <property name=" database "value=" ${gmall.redis.photo.database} "/&    Gt </bean> <bean id= "Redistemplate"class= "Org.springframework.data.redis.core.RedisTemplate"Primary= "true" > <property name= "connectionfactory" ref= "jedisconnfactory"/> <property name= "ExposeConn Ection "value=" true "/> <property name=" Keyserializer "> <Beanclass= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property Name = "ValueSerializer" > <Beanclass= "Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <pro Perty name= "Hashkeyserializer" > <Beanclass= "Org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property Name = "Hashvalueserializer" > <Beanclass= "Org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> &LT;/BEAN&G T;</beans>

2. Configuring the Mybatis-config.xml File

  

<?xml version= "1.0" encoding= "UTF-8"? ><! DOCTYPE configuration    " -//MYBATIS.ORG//DTD Config 3.0//en "    " Http://mybatis.org/dtd/mybatis-3-config.dtd "><configuration>    <settings>           <setting name= "cacheenabled" value= "true"/>    </settings></ Configuration>

3, write Rediscache implementation cache class

 PackageCom.gcard.gwmedia.cache;ImportJava.util.concurrent.locks.ReadWriteLock;ImportJava.util.concurrent.locks.ReentrantReadWriteLock;ImportOrg.apache.ibatis.cache.Cache;ImportOrg.slf4j.Logger;Importorg.slf4j.LoggerFactory;Importorg.springframework.data.redis.core.RedisTemplate;Importcom.gcard.gwmedia.utils.SpringBeanFactoryUtils; Public classRediscacheImplementsCache {Logger Logger=Loggerfactory.getlogger (GetClass ()); Private FinalString frefix = "Cache_"; Private FinalString ID; Private FinalReadwritelock Readwritelock =NewReentrantreadwritelock (true); @SuppressWarnings ("Rawtypes")    Privateredistemplate redistemplate; Private LongCleaninterval; Private Longlastclear;  PublicRediscache (String id) {if(id = =NULL){            Throw NewIllegalArgumentException ("Cache instance require an ID"); }         This. ID =ID;  This. Cleaninterval = 1 * 60 * 60 * 1000;//an hour         This. Lastclear =System.currenttimemillis (); } @SuppressWarnings ({"Unchecked"}) @Override Public voidClear () {Lastclear=System.currenttimemillis (); String strkey= Frefix +id.tostring ();        Getredistemplate (). Delete (strkey); Logger.debug ("Clear all the cached. Query result from Redis"); } @Override PublicString getId () {returnID; } @SuppressWarnings ({"Rawtypes", "unchecked"}) @Override Publicobject GetObject (Object key) {if(Key! =NULL) {String strkey= Frefix +id.tostring (); if(Clearwhenstale (strkey)) {return NULL; } redistemplate redistemplate=getredistemplate (); Object obj=Redistemplate.opsforhash (). Get (Strkey, key.tostring ()); Logger.debug ("Get cached query result from Redis"); if(obj! =NULL){                returnobj; }Else{                return NULL; }        }Else{            return NULL; }} @SuppressWarnings ("Rawtypes")    Privateredistemplate getredistemplate () {if(Redistemplate = =NULL) {redistemplate= (redistemplate) springbeanfactoryutils.getbean ("Redistemplate"); }        returnredistemplate; } @SuppressWarnings ({"Rawtypes", "unchecked"}) @Override Public voidPutObject (Object key, Object value) {if(Key! =NULL) {String strkey= Frefix +id.tostring ();            Clearwhenstale (strkey); Redistemplate redistemplate=getredistemplate ();            Redistemplate.opsforhash (). Put (strkey,key.tostring (), value); Logger.debug ("Put query result to Redis"); }} @Override PublicReadwritelock Getreadwritelock () {returnReadwritelock; } @Override Public intGetSize () {return0; } @SuppressWarnings ({"Rawtypes", "unchecked"}) @Override Publicobject Removeobject (Object key) {if(Key! =NULL) {String strkey= Frefix +id.tostring (); Redistemplate redistemplate=getredistemplate ();            Redistemplate.opsforhash (). Delete (strkey, key.tostring ()); Logger.debug ("Remove cached query result from Redis"); }        return NULL; }     Public BooleanClearwhenstale (Object key) {if(System.currenttimemillis ()-lastclear >cleaninterval) {Logger.info ("Clearwhenstale key={}", key);            Clear (); return true; }        return false; }}

4. Configuring the Mapper.xml File

Add <cache/> in Mapper.xml file

<cache type= "Com.gcard.gwmedia.cache.RedisCache"/>

5. Application Start class add annotations @enablecaching

 PackageCom.gcard.gwmedia;Importorg.springframework.boot.SpringApplication;Importorg.springframework.boot.autoconfigure.SpringBootApplication;Importorg.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;Importorg.springframework.cache.annotation.EnableCaching;ImportOrg.springframework.context.annotation.ImportResource;ImportOrg.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication (exclude= {Datasourceautoconfiguration.class}) @ImportResource (Locations= {"Classpath:/config/applicationcontext.xml"}) @EnableAsync @enablecaching Public classApplication { Public Static voidMain (string[] args) {springapplication.run (application.class, args); }    }

Springboot+mybatis+redis implementing Level Two caching

Related Article

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.