首先,需要在项目中引进jedis-2.8.1.jar包,在pom.xml里加上
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.1</version>
</dependency>
在mybatis的配置文件中加上<property name="configurationProperties">里的一段
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描mapping.xml文件 -->
<property name="mapperLocations" value="classpath:com/cn/*/mapping/*.xml"></property>
<property name="configurationProperties">
<props>
<prop key="cacheEnabled">true</prop>
<prop key="lazyLoadingEnabled">false</prop>
<prop key="aggressiveLazyLoading">true</prop>
<prop key="multipleResultSetsEnabled">true</prop>
<prop key="defaultExecutorType">REUSE</prop>
<prop key="defaultStatementTimeout">25000</prop>
</props>
</property>
<!-- <property name="configLocation" value="classpath:mybatis-config.xml" /> -->
</bean>
编写redis用到的工具类SerializeUtil.java
package com.cn.util; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class SerializeUtil {
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
//序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
//反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
return null;
}
}
}
新增一个MybatisRedisCache类,需要实现 org.apache.ibatis.cache.Cache 接口
package com.cn.util; import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ibatis.cache.Cache;
import org.apache.log4j.Logger; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; public class MybatisRedisCache implements Cache{ private Logger logger = Logger.getLogger(getClass());
private Jedis redisClient = createClient();
/** The ReadWriteLock. */
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private String id; public MybatisRedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.info(">>>>MybatisRedisCache:id=" + id);
this.id = id;
} @Override
public String getId() {
return this.id;
} @Override
public int getSize() {
return Integer.valueOf(redisClient.dbSize().toString());
} @Override
public void putObject(Object key, Object value) {
//logger.info(">>>>putObject:" + key + "=" + value);
redisClient.setex(SerializeUtil.serialize(key.toString()), 1000,SerializeUtil.serialize(value));
} @Override
public Object getObject(Object key) {
Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));
//logger.info(">>>>getObject:" + key + "=" + value);
return value;
} @Override
public Object removeObject(Object key) {
return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
} @Override
public void clear() {
redisClient.flushDB();
} @Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
} protected static Jedis createClient() {
try {
JedisPool pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1");
return pool.getResource();
} catch (Exception e) {
e.printStackTrace();
}
throw new RuntimeException("初始化连接池错误");
} }
在mapper.xml里加上
<cache type="com.cn.util.MybatisRedisCache" />
Java对象需要实现Serializable接口
package com.cn.entity; import java.io.Serializable; public class User implements Serializable{
private static final long serialVersionUID = -154635138564326678L; private Integer id; private String userName; private String password; private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password == null ? null : password.trim();
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
}
}
测试的话可以用log4j打印mybatis执行的sql语句
需要在log4j配置文件里配置:
log4j.logger.org.springframework=ERROR
log4j.logger.org.compass=ERROR
log4j.logger.org.quartz=ERROR
#log4j在控制台打印sql语句
log4j.logger.com.ibatis=DEBUG
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
#定义LOG输出级别
log4j.rootLogger=DEBUG,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d %p [%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = logs/ssm.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 1MB
# 输出所有日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n