mybatis整合redis重写 生成key的方法

来源:互联网 发布:dts hd mac 编辑:程序博客网 时间:2024/06/03 11:16
   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();
  下面是mybatis整合redis,做数据查询的语句结果缓存,我们通过mybatis redis整合实现代码和配置了解它们的技术实现:
1 实现类:
   MybatisRedisCache.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    packageapp.platform.mybatis
 
    importjava.util.concurrent.locks.ReadWriteLock; 
    importjava.util.concurrent.locks.ReentrantReadWriteLock; 
       
    importorg.apache.ibatis.cache.Cache; 
    importorg.slf4j.Logger; 
    importorg.slf4j.LoggerFactory; 
       
    importredis.clients.jedis.Jedis; 
    importredis.clients.jedis.JedisPool; 
    importredis.clients.jedis.JedisPoolConfig; 
       
/**
 * redis 整合mybatis Cache实现类
 *
 * <a href="http://www.zyiqibook.com">在一起 学习交流分享网 IT技术分享</a>
 */
    publicclass MybatisRedisCacheimplements Cache { 
           
        privatestatic Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class); 
        privateJedis redisClient=createReids(); 
         /** The ReadWriteLock. */   
        privatefinal ReadWriteLock readWriteLock =new ReentrantReadWriteLock();  
           
        privateString id; 
           
        publicMybatisRedisCache(finalString id) {   
            if(id == null) { 
                thrownew IllegalArgumentException("Cache instances require an ID"); 
            
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id="+id); 
            this.id = id; 
        }   
        @Override 
        publicString getId() { 
            returnthis.id; 
        
       
        @Override 
        publicint getSize() { 
          
            returnInteger.valueOf(redisClient.dbSize().toString()); 
        
       
        @Override 
        publicvoid putObject(Object key, Object value) { 
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value); 
            redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value)); 
        
       
        @Override 
        publicObject getObject(Object key) { 
            Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString()))); 
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:"+key+"="+value); 
            returnvalue; 
        
       
        @Override 
        publicObject removeObject(Object key) { 
            returnredisClient.expire(SerializeUtil.serialize(key.toString()),0); 
        
       
        @Override 
        publicvoid clear() { 
              redisClient.flushDB(); 
        
        @Override 
        publicReadWriteLock getReadWriteLock() { 
            returnreadWriteLock; 
        
        protected static Jedis createReids(){ 
            JedisPool pool =new JedisPool(newJedisPoolConfig(), "10.12.162.85"); 
            returnpool.getResource(); 
        }
   }

   SerializeUtil.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * redis 整合mybatis 序列化工具类
 *
 * <a href="http://www.zyiqibook.com">在一起 学习交流分享网 IT技术分享</a>
 */
    publicclass SerializeUtil { 
        publicstatic 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(); 
            returnbytes; 
            }catch (Exception e) { 
             e.printStackTrace(); 
            
            returnnull
        
                
        publicstatic Object unserialize(byte[] bytes) { 
            ByteArrayInputStream bais =null
            try
            //反序列化 
            bais =new ByteArrayInputStream(bytes); 
            ObjectInputStream ois =new ObjectInputStream(bais); 
            returnois.readObject(); 
            }catch (Exception e) { 
                
            
            returnnull
        
    }

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>
在项目中,我们可以检测到,首次查询是有语句打印,第二次则直接从redis缓存中获取。
0 1
原创粉丝点击