Spring Boot +mybatis+redis Integration

Source: Internet
Author: User
Tags connection pooling redis
Overall Thinking

There have been previous Mybatis+redis integration in the Spring Environment (http://blog.csdn.net/xiadi934/article/details/50786293). Here we try the integration in spring boot, where some of the points of attention are different. In particular, spring boot's mybatis integration can be very simple, but when adding a level two cache, we need to consider the configuration of MyBatis. join dependencies in Pom

<boot.version>1.3.1.RELEASE</boot.version> 
<dependency>
    <groupId> Org.mybatis.spring.boot</groupid>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.1.1</version>
</dependency>
<dependency>  
    <groupId> Org.springframework.boot</groupid>
    <artifactId>spring-boot-starter-redis</artifactId>
    <version>${boot.version}</version>
</dependency>
introduction of Redis configuration in Applicationcontext-cache.xml
 <!--redis data source--> <bean id= "Poolconfig" class= "Redis.clients.jedis.JedisPoolConfig" > <property n Ame= "Maxidle" value= "${spring.redis.maxidle}"/> <property name= "maxtotal" value= "${spring.redis.maxActive}"/ > <property name= "maxwaitmillis" value= "${spring.redis.maxwait}"/> <property name= "TestOnBorrow" Value= "${spring.redis.testonborrow}"/> </bean> <!--Spring-redis connection Pooling Management factory--> <bean id= " Jedisconnectionfactory "class=" Org.springframework.data.redis.connection.jedis.JedisConnectionFactory "P: Host-name= "${spring.redis.host}" p:port= "${spring.redis.port}" p:password= "${spring.redis.password}" p:
pool-config-ref= "Poolconfig"/> <!--uses intermediate classes to resolve static injection of rediscache.jedisconnectionfactory, which enables MyBatis to implement Third-party caching--> <bean id= "Rediscachetransfer" class= "Com.wedo.stream.cache.RedisCacheTransfer" > <property name= " Jedisconnectionfactory "ref=" jedisconnectionfactory/> </bean> 
Implement Cache Interface

This is exactly the same as the original. Rediscache

public class Rediscache implements Cache {private static Logger Logger = Loggerfactory.getlogger (Rediscache.class);

    private static Jedisconnectionfactory jedisconnectionfactory;

    Private final String ID;
     /** * The {@code readwritelock}.

    * Private final Readwritelock Readwritelock = new Reentrantreadwritelock (); Public Rediscache (final String ID) {if (id = = null) {throw new IllegalArgumentException ("Cache Insta
        NCEs require an ID ");
        } logger.debug ("mybatisrediscache:id=" + ID);
    This.id = ID;
        @Override public void Clear () {jedisconnection connection = null;
            try {connection = jedisconnectionfactory.getconnection ();
            Connection.flushdb ();
        Connection.flushall ();
        catch (Jedisconnectionexception e) {e.printstacktrace ();
        finally {if (connection!= null) {connection.close ();    @Override public String getId () {return this.id;
        @Override public Object GetObject (object key) {object = null;
        Jedisconnection connection = null;
            try {connection = jedisconnectionfactory.getconnection ();
            Redisserializer<object> serializer = new Jdkserializationredisserializer ();
        result = Serializer.deserialize (Connection.get (Serializer.serialize (key));
        catch (Jedisconnectionexception e) {e.printstacktrace ();
            finally {if (connection!= null) {connection.close ();
    } return result;
    @Override public Readwritelock Getreadwritelock () {return this.readwritelock;
        @Override public int GetSize () {int. result = 0;
        Jedisconnection connection = null; try {connection = Jedisconnectionfactory.getconnection ();
        result = Integer.valueof (Connection.dbsize (). toString ());
        catch (Jedisconnectionexception e) {e.printstacktrace ();
            finally {if (connection!= null) {connection.close ();
    } return result;
        @Override public void Putobject (object key, Object value) {jedisconnection connection = null;
            try {connection = jedisconnectionfactory.getconnection ();
            Redisserializer<object> serializer = new Jdkserializationredisserializer ();
        Connection.set (Serializer.serialize (key), serializer.serialize (value));
        catch (Jedisconnectionexception e) {e.printstacktrace ();
            finally {if (connection!= null) {connection.close ();
        @Override public Object Removeobject (object key) {jedisconnection connection = null; Object result =Null
            try {connection = jedisconnectionfactory.getconnection ();
            Redisserializer<object> serializer = new Jdkserializationredisserializer ();
        result = Connection.expire (Serializer.serialize (key), 0);
        catch (Jedisconnectionexception e) {e.printstacktrace ();
            finally {if (connection!= null) {connection.close ();
    } return result; public static void Setjedisconnectionfactory (Jedisconnectionfactory jedisconnectionfactory) {Rediscach
    E.jedisconnectionfactory = jedisconnectionfactory;
 }

}
Rediscachetransfer
public class Rediscachetransfer 
{
    @Autowired the public
    void Setjedisconnectionfactory ( Jedisconnectionfactory jedisconnectionfactory)     {
        rediscache.setjedisconnectionfactory ( jedisconnectionfactory);
    }


Add in configuration file Application.yml
#Redis Settings  
Spring:
 redis:
  host:127.0.0.1
  password:aaa
  port:6379
mybatis:
 mapperlocations:classpath*:com/wedo/stream/dao/xml/*.xml
 typealiasespackage: Com.wedo.stream.dao.entity
 Configlocation:classpath:mybatis-config.xml
mybatis Global Configuration Mybatis-config.xml

Note that this was originally unwanted, and the MyBatis default is to turn on level two caching. But we added the configuration to turn off the level two cache for testing.

<?xml version= "1.0" encoding= "UTF-8"?> <! DOCTYPE configuration Public "-//mybatis.org//dtd Config 3.0//en" "Http://mybatis.org/dtd/mybatis-3-config . DTD "> <configuration> <settings> <!--open Hump matching--> <setting name=" Mapunderscor Etocamelcase "value= true"/> <!--This configuration enables the global mapper to enable or disable caching. The system defaults are true and the settings are only displayed to show--> <setting name= "cacheenabled" value= "true"/> <!--global Enable or disable deferred loading.     When disabled, all associated objects are loaded instantly. The system defaults are true, setting is only to show--> <setting name= "lazyloadingenabled" value= "true"/> <!--allow or disallow multiple result sets from     Returns in a separate statement (requires the appropriate driver). The system defaults are true, setting is just to show--> <setting name= "multipleresultsetsenabled" value= "true"/> <!--use column labels instead Replace the column name. Different drives differ in this convenient performance. Refer to the driver document or fully test both methods to determine the driver used. The system defaults are true, and the settings are just for display--> <setting name= "Usecolumnlabel" value= "true"/> <!--allow JDBC to support the generated keys. Need to fit the driver. 
If set to true, this setting forces the generated keys to be used, although some drivers are rejected compatible but still valid (e.g.            Derby). The system defaults are false and are set only to show--> <setting name= "Usegeneratedkeys" value= "false"/> <!--Configure the default executor. There's nothing special about simple actuators. A preprocessing statement is used by the reuse execution.
        BATCH the default value of the statement and batch update system is simple, setting is just to show up--> <setting name= "Defaultexecutortype" value= "simply"/>     <!--Set the timeout time, which determines when the driver waits for a database response.
The system defaults are null, setting is just to show--> <setting name= "defaultstatementtimeout" value= "25000"/> </settings>
 </configuration>
add MyBatis Level two cache in mapper
<mapper namespace= "Com.wedo.stream.dao.mapper.SorterMapper" >
  <cache type= " Com.wedo.stream.cache.RedisCache "/>
..... </mapper>  
entity class implementation Serializable

public class Sorter implements Serializable test

@RunWith (Springjunit4classrunner.class)
@ContextConfiguration (locations = {"/spring-dao.xml", "/ Applicationcontext-cache.xml "}"
@ActiveProfiles (value= "Dev")
@TestExecutionListeners ({ Dependencyinjectiontestexecutionlistener.class,
    Dbunittestexecutionlistener.class}) public
class cachetest {
    private static Logger Logger = Loggerfactory.getlogger (cachetest.class);
    @Autowired
    Private Sortermapper mapper;
    @Test public
    void Test () {
        date start = new Date ();
        for (int i=0;i<100;i++) {
            mapper.getall ();
        }
        Date end = new Date ();
        Long Duration = End.gettime ()-start.gettime ();
        Logger.info (duration);
    }

Test results, if the level two cache is turned on, spents 363 milliseconds, and if the two level cache is turned off 6 seconds +, the average query is 50 milliseconds.

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.