redis学习总结-redis作为MyBatis的自定义缓存
1、RedisCache.java
package com.houtai.cache; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.ibatis.cache.Cache; import org.apache.ibatis.logging.Log; import org.apache.ibatis.logging.LogFactory; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class RedisCache implements Cache { private static Log logger = LogFactory.getLog(RedisCache.class); private Jedis redisClient = createClient(); /** The ReadWriteLock. */ private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private String id; public RedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id); this.id = id; } public String getId() { return this.id; } public int getSize() { return Integer.valueOf(redisClient.dbSize().toString()); } public void putObject(Object key, Object value) { logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value); redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil .serialize(value)); } public Object getObject(Object key) { Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil .serialize(key.toString()))); logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value); return value; } public Object removeObject(Object key) { return redisClient.expire(SerializeUtil.serialize(key.toString()), 0); } public void clear() { redisClient.flushDB(); } public ReadWriteLock getReadWriteLock() { return readWriteLock; } protected static Jedis createClient() { try { JedisPool pool = new JedisPool(new JedisPoolConfig(), "localhost"); return pool.getResource(); } catch (Exception e) { e.printStackTrace(); } throw new RuntimeException("初始化连接池错误"); } }
2、序列化与方序列化工具类
package com.houtai.cache; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * * @author 作者: wcy * @version 创建时间:Mar 20, 2015 3:27:39 PM * @Description: TODO(用于序列化键值对) */ 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) { if (bytes == null) return null; ByteArrayInputStream bais = null; try { // 反序列化 bais = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; } }
3、自定义缓存的入口,继承MyBatis的loggingCache类
package com.houtai.cache; import org.apache.ibatis.cache.decorators.LoggingCache; public class LoggingRedisCache extends LoggingCache{ public LoggingRedisCache(String id) { super(new RedisCache(id)); // TODO Auto-generated constructor stub } }
4、同时配置MyBatis的配置文件
<?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> <settings> <!-- 这个配置使全局的映射器启用或禁用缓存 --> <setting name="cacheEnabled" value="true" /> <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> <setting name="multipleResultSetsEnabled" value="true" /> <!-- 配置默认的执行器。SIMPLE 执行器没有什么特别之处。REUSE 执行器重用预处理语句。BATCH 执行器重用语句和批量更新 --> <setting name="defaultExecutorType" value="REUSE" /> <!-- 全局启用或禁用延迟加载。当禁用时,所有关联对象都会即时加载。 --> <setting name="lazyLoadingEnabled" value="false" /> <setting name="aggressiveLazyLoading" value="true" /> <!-- <setting name="enhancementEnabled" value="true"/> --> <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间。 --> <setting name="defaultStatementTimeout" value="25000" /> </settings> <typeAliases> <package name="com.houtai.model" /> </typeAliases> <mappers> <mapper resource="sqlmap/houtai/accountMapper.xml" /> <mapper resource="sqlmap/houtai/categoryMapper.xml" /> <mapper resource="sqlmap/houtai/goodsMapper.xml" /> <mapper resource="sqlmap/houtai/sorderMapper.xml" /> <mapper resource="sqlmap/houtai/forderMapper.xml" /> </mappers> </configuration>
5、因为使用MyBatis的二级缓存,所以要缓存的类,必须开启<cache/>
<?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="com.houtai.model.Account"> <!-- redis缓存 --> <cache eviction="LRU" type="com.houtai.cache.LoggingRedisCache"/>
<select id="loginAccount" parameterType="account" resultType="account" useCache="true"> select * from account a where a.login=#{login} and a.pass=#{pass} </select> </mapper>
6、最后测试通过。