半只蚂蚁 发表于 2016-11-26 04:45:43

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 实现类:
 view plaincopy 



[*]package app.platform.mybatis

[*]

[*]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 redis.clients.jedis.Jedis;  
[*]import redis.clients.jedis.JedisPool;  
[*]import redis.clients.jedis.JedisPoolConfig;  
[*]  
[*]  
[*]public class MybatisRedisCache implements Cache {  
[*]      
[*]    private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);  
[*]    private Jedis redisClient=createReids();  
[*]     /** 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.debug(">>>>>>>>>>>>>>>>>>>>>>>>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.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);  
[*]        redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));  
[*]    }  
[*]  
[*]    @Override  
[*]    public Object getObject(Object key) {  
[*]        Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));  
[*]        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>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 createReids(){  
[*]        JedisPool pool = new JedisPool(new JedisPoolConfig(), "10.12.162.85");  
[*]        return pool.getResource();  
[*]    }  

 view plaincopy 



[*]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;  
[*]        }  

  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,按他的方式没配置成功,按上面的方式修改后成功
页: [1]
查看完整版本: Mybatis自定义缓存——Redis实现