使用Redis做Mybatis二級緩存

介紹

  1. 使用mybatis時可以使用二級緩存提高查詢速度,進(jìn)而改善用戶體驗。
  2. 使用redis做mybatis的二級緩存可是內(nèi)存可控<如將單獨(dú)的服務(wù)器部署出來用于二級緩存>,管理方便。

相關(guān)jar包

jedis-2.9.0.jar  
spring-data-commons-1.13.7.RELEASE.jar
spring-data-keyvalue-1.2.7.RELEASE.jar
spring-data-redis-1.8.7.RELEASE.jar
使用思路
  1. 配置redis.xml 設(shè)置redis服務(wù)連接各參數(shù)
  2. 在配置文件中使用 標(biāo)簽,設(shè)置開啟二級緩存
  3. 在mapper.xml 中使用 將cache映射到指定的RedisCacheClass類中
  4. 映射類RedisCacheClass 實(shí)現(xiàn) MyBatis包中的Cache類,并重寫其中各方法
  • 在重寫各方法體中,使用redisFactory和redis服務(wù)建立連接,將緩存的數(shù)據(jù)加載到指定的redis內(nèi)存中(putObject方法)或?qū)edis服務(wù)中的數(shù)據(jù)從緩存中讀取出來(getObject方法);

  • 在redis服務(wù)中寫入和加載數(shù)據(jù)時需要借用spring-data-redis.jar中JdkSerializationRedisSerializer.class中的序列化(serialize)和反序列化方法(deserialize),此為包中封裝的redis默認(rèn)的序列化方法

  1. 映射類中的各方法重寫完成后即可實(shí)現(xiàn)mybatis數(shù)據(jù)二級緩存到redis服務(wù)中

代碼實(shí)踐

  1. 在springmvc.xml 中配置redis相關(guān)配置、或者直接寫redis.xml
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd" >

<!-- enable autowire -->

 <context:annotation-config /> 

<task:annotation-driven/>

<context:component-scan base-package="demo.util,demo.salesorder,demo.person" />
<!-- Configures the @Controller programming model 必須加上這個,不然請求controller時會出現(xiàn)no mapping url錯誤-->
<mvc:annotation-driven />
<!-- 引入數(shù)據(jù)庫配置文件 -->
<bean id="propertyConfigurer"    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:sysconfig/jdbc.properties</value>
            <value>classpath:sysconfig/redis.properties</value>
        </list>
    </property>
</bean>
<!-- JDBC -->
<bean id="defaultDataSource"   class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.databaseurl}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" >
    <property name="maxActive">
        <value>${jdbc.maxActive}</value>
    </property>  
    <property name="initialSize">
        <value>${jdbc.initialSize}</value>
    </property>  
    <property name="maxWait">
        <value>${jdbc.maxWait}</value>
    </property>  
    <property name="maxIdle">
        <value>${jdbc.maxIdle}</value>
    </property>
    <property name="minIdle">
        <value>${jdbc.minIdle}</value>
    </property>
    <!-- 只要下面兩個參數(shù)設(shè)置成小于8小時(MySql默認(rèn)),就能避免MySql的8小時自動斷開連接問題 -->
    <property name="timeBetweenEvictionRunsMillis">
        <value>18000000</value>
    </property><!-- 5小時 -->
    <property name="minEvictableIdleTimeMillis">
        <value>10800000</value>
    </property><!-- 3小時 -->
    <property name="validationQuery">
        <value>SELECT 1</value>
    </property>
    <property name="testOnBorrow">
        <value>true</value>
    </property>
</bean>

<!-- define the SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="defaultDataSource" />
    <property name="typeAliasesPackage" value="demo.salesorder,demo.person" />
    <!-- 可以單獨(dú)指定mybatis的配置文件,或者寫在本文件里面。 用下面的自動掃描裝配(推薦)或者單獨(dú)mapper --> 
    <property name="configLocation" value="classpath:sysconfig/mybatis-config.xml" />
</bean>


<!-- 自動掃描并組裝MyBatis的映射文件和接口-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="demo.*.data" />
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>

<!-- JDBC END -->

<!-- redis數(shù)據(jù)源 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
    <property name="maxIdle" value="${redis.maxIdle}" />  
    <property name="maxTotal" value="${redis.maxActive}" />  
    <property name="maxWaitMillis" value="${redis.maxWait}" />  
    <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
</bean>

<!-- Spring-redis連接池管理工廠 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
    <property name="hostName" value="${redis.host}" />
    <property name="port" value="${redis.port}" />
    <property name="password" value="${redis.pass}" />
    <property name="timeout" value="${redis.timeout}" />
    <property name="poolConfig" ref="poolConfig" />
</bean>      
<!-- 使用中間類解決RedisCache.jedisConnectionFactory的靜態(tài)注入,從而使MyBatis實(shí)現(xiàn)第三方緩存 -->
<bean id="redisCacheTransfer" class="demo.redis.RedisCacheTransfer">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>      

<bean class="demo.util.UTF8StringBeanPostProcessor"></bean>          
</beans>    
  1. mybatis.xml 配置開啟二級緩存

     <?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> 
     <!-- 配置mybatis的緩存,延遲加載等等一系列屬性 -->
       <settings>
     <!-- 全局映射器啟用緩存 *主要將此屬性設(shè)置完成即可-->
     <setting name="cacheEnabled" value="true"/>
    
     <!-- 查詢時,關(guān)閉關(guān)聯(lián)對象即時加載以提高性能 -->
     <setting name="lazyLoadingEnabled" value="false"/>
    
     <!-- 對于未知的SQL查詢,允許返回不同的結(jié)果集以達(dá)到通用的效果 -->
     <setting name="multipleResultSetsEnabled" value="true"/>
    
     <!-- 設(shè)置關(guān)聯(lián)對象加載的形態(tài),此處為按需加載字段(加載字段由SQL指 定),不會加載關(guān)聯(lián)表的所有字段,以提高性能 -->
     <setting name="aggressiveLazyLoading" value="true"/>
    
    </settings>
    </configuration>
    
  2. 在mapper.xml中映射緩存類RedisCacheClass

      <?xml version="1.0" encoding="UTF-8"?>
     <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
     "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
     <mapper namespace="demo.person.data.UserMapper">
     <cache type="demo.redis.cache.RedisCache"/> <!-- *映射語句 -->
    
     <select id="getPersonList" parameterType="map" resultType="Person">
         select *    
          from person
         <where>
             1=1
             <if test="user_name!=null">
                 and user_name=#{user_name}
             </if>    
         </where>
     </select>
     <insert id="addPerson" parameterType="Person" keyProperty="id" useGeneratedKeys="true">
         insert into person(
             login_id,
             user_name,
             gender,
             birthday,
             remark
         )values(
             #{login_id},
             #{user_name},
             #{gender},
             #{birthday},
             #{remark}
         )
     </insert>
    
     </mapper>
    
  3. 實(shí)現(xiàn)Mybatis中的Cache接口

  • Cache.class源碼:

      /*
       *    Copyright 2009-2012 the original author or authors.
       *    http://www.apache.org/licenses/LICENSE-2.0*/
      package org.apache.ibatis.cache;
    
      import java.util.concurrent.locks.ReadWriteLock;
    
      public interface Cache {
    
        String getId();
    
        int getSize();
    
        void putObject(Object key, Object value);
    
        Object getObject(Object key);
    
        Object removeObject(Object key);
    
        void clear();
    
        ReadWriteLock getReadWriteLock();
    
      }
    
  • RedisCache.java

      package demo.redis.cache;
    
      import java.util.concurrent.locks.ReadWriteLock;
      import java.util.concurrent.locks.ReentrantReadWriteLock;
    
      import org.apache.ibatis.cache.Cache;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.data.redis.connection.jedis.JedisConnection;
      import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
      import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
      import org.springframework.data.redis.serializer.RedisSerializer;
    
      import redis.clients.jedis.exceptions.JedisConnectionException;
    
    
      public class RedisCache implements Cache //實(shí)現(xiàn)類
      {
          private static final 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 instances require an ID");
              }
              logger.debug("MybatisRedisCache:id=" + id);
              this.id = id;
          }
    
          @Override
          public void clear()
          {
              JedisConnection connection = null;
              try
              {
                  connection = jedisConnectionFactory.getConnection(); //連接清除數(shù)據(jù)
                  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 result = null;
              JedisConnection connection = null;
              try
              {
                  connection = jedisConnectionFactory.getConnection();
                  RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer(); //借用                spring_data_redis.jar中的JdkSerializationRedisSerializer.class
                  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
              {
                  logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);
                  connection = jedisConnectionFactory.getConnection();
                  RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer(); //借用        spring_data_redis.jar中的JdkSerializationRedisSerializer.class
                  connection.set(serializer.serialize(key), serializer.serialize(value)); //利用其序列化方法將數(shù)據(jù)寫入redis服務(wù)的緩存中
    
              }
              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) {
              RedisCache.jedisConnectionFactory = jedisConnectionFactory;
          }
    
      }
    
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • 前言 主題是Mybatis一級和二級緩存的應(yīng)用及源碼分析。希望在本場chat結(jié)束后,能夠幫助讀者朋友明白以下三點(diǎn)。...
    余平的余_余平的平閱讀 1,418評論 0 12
  • 文/清微淡遠(yuǎn) 傍晚,去超市,購保溫桶,準(zhǔn)備給住校的娃兒加餐用。導(dǎo)購員很熱心,推薦了幾款,聽其介紹了性能、價位,決定...
    玲瓏雪閱讀 308評論 0 0
  • 做最簡單的自己,做好自己,只有做好了自己,才可以談別的東西。放下我執(zhí),即可成長。
    這只是一個樹洞閱讀 339評論 0 0
  • 風(fēng)來了 我想隨他四處闖闖 找到一個地方 那里會充滿著陽光 風(fēng)來了 我想隨他四處闖闖 找到一個地方 那里會讓人放下憂...
    筱步田閱讀 186評論 2 2

友情鏈接更多精彩內(nèi)容