1. 介绍
使用mybatis时可以使用二级缓存提高查询速度,进而改善用户体验。
使用redis做mybatis的二级缓存可是内存可控<如将单独的服务器部署出来用于二级缓存>,管理方便。
2. 使用思路
a. 配置redis.xml 设置redis服务连接各参数
b. 在配置文件中使用 <setting> 标签,设置开启二级缓存;
c. 在mapper.xml 中使用<cache type="com.demo.RedisCacheClass" /> 将cache映射到指定的RedisCacheClass类中;
d. 映射类RedisCacheClass 实现 MyBatis包中的Cache类,并重写其中各方法;
d1.在重写各方法体中,使用redisFactory和redis服务建立连接,将缓存的数据加载到指定的redis内存中(putObject方法)或将redis服务中的数据从缓存中读取出来(getObject方法);
d2.在redis服务中写入和加载数据时需要借用spring-data-redis.jar中JdkSerializationRedisSerializer.class中的序列化(serialize)和反序列化方法(deserialize),此为包中封装的redis默认的序列化方法;
e. 映射类中的各方法重写完成后即可实现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"