使用Redis做MyBatis的二級快取
轉載地址: http://www.cnblogs.com/springlight/p/6374372.html
1. 介紹
使用mybatis時可以使用二級快取提高查詢速度,進而改善使用者體驗。
使用redis做mybatis的二級快取可是記憶體可控<如將單獨的伺服器部署出來用於二級快取>,管理方便。
2. 使用思路
2.1 配置redis.xml 設定redis服務連線各引數
2.1 在配置檔案中使用 <setting> 標籤,設定開啟二級快取;
2.2 在mapper.xml 中使用<cache type="com.demo.RedisCacheClass" /> 將cache對映到指定的RedisCacheClass類中;
2.3 對映類RedisCacheClass 實現 MyBatis包中的Cache類,並重寫其中各方法;
在重寫各方法體中,使用redisFactory和redis服務建立連線,將快取的資料載入到指定的redis記憶體中(putObject方法)或將redis服務中的資料從快取中讀取出來(getObject方法);
在redis服務中寫入和載入資料時需要借用spring-data-redis.jar中JdkSerializationRedisSerializer.class中的序列化(serialize)和反序列化方法(deserialize),此為包中封裝的redis預設的序列化方法;
2.4 對映類中的各方法重寫完成後即可實現mybatis資料二級快取到redis服務中;
3. 程式碼實踐
3.1 配置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>
3.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>
3.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>
3.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();