Mybatis自定义缓存——Redis实现

mybatis默认缓存是PerpetualCache,可以查看一下它的源码,发现其是Cache接口的实现;那么我们的缓存只要实现该接口即可。

该接口有以下方法需要实现:

  String getId();
  int getSize();
  void putObject(Object key, Object value);
  Object getObject(Object key);
  Object removeObject(Object key);
  void clear();
  ReadWriteLock getReadWriteLock();

1 实现类:

[java]  view plain copy
 
  1. package app.platform.mybatis

  2. import java.util.concurrent.locks.ReadWriteLock;  
  3. import java.util.concurrent.locks.ReentrantReadWriteLock;  
  4.   
  5. import org.apache.ibatis.cache.Cache;  
  6. import org.slf4j.Logger;  
  7. import org.slf4j.LoggerFactory;  
  8.   
  9. import redis.clients.jedis.Jedis;  
  10. import redis.clients.jedis.JedisPool;  
  11. import redis.clients.jedis.JedisPoolConfig;  
  12.   
  13.   
  14. public class MybatisRedisCache implements Cache {  
  15.       
  16.     private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);  
  17.     private Jedis redisClient=createReids();  
  18.      /** The ReadWriteLock. */    
  19.     private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();   
  20.       
  21.     private String id;  
  22.       
  23.     public MybatisRedisCache(final String id) {    
  24.         if (id == null) {  
  25.             throw new IllegalArgumentException("Cache instances require an ID");  
  26.         }  
  27.         logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id="+id);  
  28.         this.id = id;  
  29.     }    
  30.     @Override  
  31.     public String getId() {  
  32.         return this.id;  
  33.     }  
  34.   
  35.     @Override  
  36.     public int getSize() {  
  37.      
  38.         return Integer.valueOf(redisClient.dbSize().toString());  
  39.     }  
  40.   
  41.     @Override  
  42.     public void putObject(Object key, Object value) {  
  43.         logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);  
  44.         redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));  
  45.     }  
  46.   
  47.     @Override  
  48.     public Object getObject(Object key) {  
  49.         Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));  
  50.         logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:"+key+"="+value);  
  51.         return value;  
  52.     }  
  53.   
  54.     @Override  
  55.     public Object removeObject(Object key) {  
  56.         return redisClient.expire(SerializeUtil.serialize(key.toString()),0);  
  57.     }  
  58.   
  59.     @Override  
  60.     public void clear() {  
  61.           redisClient.flushDB();  
  62.     }  
  63.     @Override  
  64.     public ReadWriteLock getReadWriteLock() {  
  65.         return readWriteLock;  
  66.     }  
  67.     protected  static Jedis createReids(){  
  68.         JedisPool pool = new JedisPool(new JedisPoolConfig(), "10.12.162.85");  
  69.         return pool.getResource();  
  70.     }  
[java]  view plain copy
 
  1. public class SerializeUtil {  
  2.     public static byte[] serialize(Object object) {  
  3.         ObjectOutputStream oos = null;  
  4.         ByteArrayOutputStream baos = null;  
  5.         try {  
  6.         //序列化  
  7.         baos = new ByteArrayOutputStream();  
  8.         oos = new ObjectOutputStream(baos);  
  9.         oos.writeObject(object);  
  10.         byte[] bytes = baos.toByteArray();  
  11.         return bytes;  
  12.         } catch (Exception e) {  
  13.          e.printStackTrace();  
  14.         }  
  15.         return null;  
  16.         }  
  17.            
  18.         public static Object unserialize(byte[] bytes) {  
  19.         ByteArrayInputStream bais = null;  
  20.         try {  
  21.         //反序列化  
  22.         bais = new ByteArrayInputStream(bytes);  
  23.         ObjectInputStream ois = new ObjectInputStream(bais);  
  24.         return ois.readObject();  
  25.         } catch (Exception e) {  
  26.            
  27.         }  
  28.         return null;  
  29.         }  

2 spring中的mybatis配置

<!-- mybatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath*:app/mapper/**/*.xml"/>
       <property name="configLocation" value="classpath:/mybatis/mybatis-config.xml" />
</bean>


3 mybatis-config.xml 中的settings配制

<settings>
<!-- 开启缓存支持 -->  
<setting name="cacheEnabled" value="true" />
....... 
</settings>

 

4 在需要加缓存的sqlMap中加入<cache eviction="LRU" type="app.platform.mybatis.MybatisRedisCache" />

例:

<mapper namespace="SYS_ROLE">

  <!-- 缓存 -->
  <cache eviction="LRU" type="app.platform.mybatis.MybatisRedisCache" />

   <!-- 查询所有 -->
<select id="findAll" parameterType="HashMap" resultType="HashMap">
select 
<include refid="base_column" />
from SYS_ROLE
where 1=1
<if test="BUS_TYPE!=null and BUS_TYPE!=''">
and BUS_TYPE  =#{BUS_TYPE}
</if>
<if test="ENABLE!=null and ENABLE!=''">
and ENABLE  =#{ENABLE}
</if>
<if test="ROLE_NAME!=null and ROLE_NAME!=''">
and ROLE_NAME like '%'||#{ROLE_NAME}||'%'
</if>
<if test="ROLE_OTHER_NAME!=null and ROLE_OTHER_NAME!=''">
and ROLE_OTHER_NAME like '%'||#{ROLE_OTHER_NAME}||'%'
</if>
</select>

</mapper>



本文参考了http://blog.csdn.net/nmgrlq/article/details/7996925,按他的方式没配置成功,按上面的方式修改后成功

猜你喜欢

转载自steveoyung.iteye.com/blog/2066458