使用Redis做Mybatis二級緩存

1. 介紹

使用mybatis時可以使用二級緩存提高查詢速度,進而改善用戶體驗。

使用redis做mybatis的二級緩存可是內存可控<如將單獨的服務器部署出來用於二級緩存>,管理方便。

2. 相關Jar包

2.1).jedis-2.9.0.jar  
2.2).spring-data-commons-1.13.7.RELEASE.jar
2.3).spring-data-keyvalue-1.2.7.RELEASE.jar

2.4).spring-data-redis-1.8.7.RELEASE.jar

3. 實現思路

3.1). 配置redis.xml 設置redis服務連接各參數;
3.2). 在配置文件中使用 <setting> 標籤,設置開啓二級緩存;
3.3). 在mapper.xml 中使用<cache type="com.demo.RedisCacheClass" /> 將cache映射到指定的RedisCacheClass類中;
3.4).映射類RedisCacheClass 實現 MyBatis包中的Cache類,並重寫其中各方法;

    在重寫各方法體中,使用redisFactory和redis服務建立連接,將緩存的數據加載到指定的redis內存中(putObject方法)或將redis服務中的數據從緩存中讀取出來(getObject方法);

    在redis服務中寫入和加載數據時需要借用spring-data-redis.jar中JdkSerializationRedisSerializer.class中的序列化(serialize)和反序列化方法(deserialize),此爲包中封裝的redis默認的序列化方法;

3.5).映射類中的各方法重寫完成後即可實現mybatis數據二級緩存到redis服務中;

4. 代碼實踐

4.1).在springmvc.xml 中配置redis相關配置、或者直接寫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時會出現no mapping url錯誤-->
    <mvc:annotation-driven />
    <!-- 引入數據庫配置文件 -->
    <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>
        <!-- 只要下面兩個參數設置成小於8小時(MySql默認),就能避免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" />
        <!-- 可以單獨指定mybatis的配置文件,或者寫在本文件裏面。 用下面的自動掃描裝配(推薦)或者單獨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數據源 -->
    <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的靜態注入,從而使MyBatis實現第三方緩存 -->
    <bean id="redisCacheTransfer" class="demo.redis.RedisCacheTransfer">
        <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
    </bean>      
    
    <bean class="demo.util.UTF8StringBeanPostProcessor"></bean>          

</beans> 

4.2 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>
        <!-- 全局映射器啓用緩存 *主要將此屬性設置完成即可-->

        <setting name="cacheEnabled" value="true"/>

        <!-- 查詢時,關閉關聯對象即時加載以提高性能 -->

        <setting name="lazyLoadingEnabled" value="false"/>

        <!-- 對於未知的SQL查詢,允許返回不同的結果集以達到通用的效果 -->
        <setting name="multipleResultSetsEnabled" value="true"/>

        <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指 定),不會加載關聯表的所有字段,以提高性能 -->
        <setting name="aggressiveLazyLoading" value="true"/>
    </settings>
</configuration>   

4.3 在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>

4.4 實現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 //實現類
{
    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(); //連接清除數據
            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)); //利用其序列化方法將數據寫入redis服務的緩存中
            
        }
        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;
    }

}



發佈了75 篇原創文章 · 獲贊 8 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章