介紹
- 使用mybatis時可以使用二級緩存提高查詢速度盒揉,進(jìn)而改善用戶體驗。
- 使用redis做mybatis的二級緩存可是內(nèi)存可控<如將單獨的服務(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
使用思路
- 配置redis.xml 設(shè)置redis服務(wù)連接各參數(shù)
- 在配置文件中使用 標(biāo)簽,設(shè)置開啟二級緩存
- 在mapper.xml 中使用 將cache映射到指定的RedisCacheClass類中
- 映射類RedisCacheClass 實現(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)的序列化方法
- 映射類中的各方法重寫完成后即可實現(xiàn)mybatis數(shù)據(jù)二級緩存到redis服務(wù)中
代碼實踐
- 在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" />
<!-- 可以單獨指定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數(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實現(xiàn)第三方緩存 -->
<bean id="redisCacheTransfer" class="demo.redis.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>
<bean class="demo.util.UTF8StringBeanPostProcessor"></bean>
</beans>
-
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>
-
在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>
實現(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 //實現(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; } }