mybatis的二级缓存--配置redis缓存

  1. mybatis的二级缓存是以namespace为单位的,不同namespace下的操作互不影响。

          1. insert,update,delete操作会清空所在namespace下的全部缓存。

  2. 通常使用MyBatis Generator生成的代码中,都是各个表独立的,每个表都有自己的namespace。所以对于一个表的操作,最好放到一个namespace下面,便于更新缓存



1 使用到的jar包,maven

<!-- spring-redis实现 -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.6.2.RELEASE</version>
</dependency>
<!-- redis客户端jar -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
</dependency>

2 application.xml配置 redis数据源
<!-- redis数据源-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">  
    <property name="maxIdle" value="${redis.maxIdle}" />  
    <property name="maxTotal" value="${redis.maxActive}" />  
    <property name="maxWaitMillis" value="${redis.maxWait}" />  
    <property name="testOnBorrow" value="${redis.testOnBorrow}" /> 
    <property name="testWhileIdle" value="${redis.testWhileIdle}" />
    <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}" />
    <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}" />
    <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}" /> 
</bean>
<!-- Spring-redis连接池管理工厂 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
    p:host-name="${redis.host}" 
    p:port="${redis.port}" 
    p:password="${redis.pass}" 
     p:pool-config-ref="poolConfig"/> 
<!-- 使用中间类解决RedisCache.jedisConnectionFactory的静态注入,从而使MyBatis实现第三方缓存  -->
<bean id="redisCacheTransfer" class="com.youlh.redis.cache.RedisCacheTransfer">
    <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>

3  自定义的一些java类
(1) RedisCacheMy.java
package com.youlh.redis.cache;

import java.io.UnsupportedEncodingException;
import java.util.Set;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.apache.log4j.Logger;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import com.common.Commonparam;

import redis.clients.jedis.exceptions.JedisConnectionException;



public class RedisCacheMy  implements Cache{
	private static final Logger logger = Logger.getLogger(RedisCacheMy.class);

	private static JedisConnectionFactory jedisConnectionFactory;

    private final String id;
    private static final int DB_INDEX = 1;
    /**
     * The {@code ReadWriteLock}.
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public RedisCacheMy(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.debug("MybatisRedisCache:id=" + id);
        this.id = id;
        
    }
   
	//删除更新的空间keys
    public void clear()
    {
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.select(DB_INDEX);
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            logger.debug("*"+this.getId()+"*");
          
			try {
				Set<byte[]> keys;
				keys = connection.keys((new String("*:"+this.getId()+".*")).getBytes("utf-8"));
				for (byte[] key : keys) {
					logger.debug(new String(key));
	            	connection.del(key);
	            }
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
          
            
          //下面是网上流传的方法,极大的降低系统性能,没起到加入缓存应有的作用,这是不可取的。
//          connection.flushDb();
//          connection.flushAll();
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }
    
    //删除更新的空间keys
    public static void clearMy(String id)
    {
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.select(DB_INDEX);
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            logger.debug("*"+id+"*");
          
			try {
				Set<byte[]> keys;
				keys = connection.keys((new String("*"+id+"*")).getBytes("utf-8"));
				for (byte[] key : keys) {
					logger.debug(new String(key));
	            	connection.del(key);
	            }
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
          
            
          //下面是网上流传的方法,极大的降低系统性能,没起到加入缓存应有的作用,这是不可取的。
//          connection.flushDb();
//          connection.flushAll();
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    public String getId()
    {
        return this.id;
    }
    
    public  Object getObject(Object key)
    {
    	logger.debug(Commonparam.Date2Str()+"---redis getObject key--->"+key);
        Object result = null;
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.select(DB_INDEX);
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            try {
				result = serializer.deserialize(connection.get(key.toString().getBytes("utf-8")));
			} catch (SerializationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    public ReadWriteLock getReadWriteLock()
    {
        return this.readWriteLock;
    }

    public int getSize()
    {
        int result = 0;
        JedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.select(DB_INDEX);
            result = Integer.valueOf(connection.dbSize().toString());
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    public void putObject(Object key, Object value)
    {
    	logger.debug(Commonparam.Date2Str()+"-->redis putObject  key -->"+key);
        JedisConnection connection = null;
        try
        {
        
            
            connection = jedisConnectionFactory.getConnection();
            connection.select(DB_INDEX);
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            try {
            	//有效时间
            	Object second=Commonparam.getRedisPropertyByKey(this.getId());
            	if(second==null){
            		second=60*60;//1小时
            	}
            	connection.setEx(key.toString().getBytes("utf-8"),Integer.valueOf(second.toString()), serializer.serialize(value));
//				connection.set(key.toString().getBytes("utf-8"),serializer.serialize(value));
			} catch (SerializationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
//            
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    public Object removeObject(Object key)
    {
        JedisConnection connection = null;
        Object result = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.select(DB_INDEX);
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            try {
				result =connection.expire(key.toString().getBytes("utf-8"), 0);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

    public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        RedisCacheMy.jedisConnectionFactory = jedisConnectionFactory;
    }
}

(2)LoggingRedisCache.java
package com.youlh.redis.cache;

import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.decorators.LoggingCache;

/**
 * 自定义缓存的入口,继承MyBatis的loggingCache类
 * @author zhaoruike
 *
 */
public class LoggingRedisCache extends LoggingCache{
 
    public LoggingRedisCache(String id) {
        super(new RedisCacheMy(id));
        // TODO Auto-generated constructor stub
    }
 

}

(2)RedisCacheTransfer.java
package com.youlh.redis.cache;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

public class RedisCacheTransfer {
	 @Autowired
	    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
		 RedisCacheMy.setJedisConnectionFactory(jedisConnectionFactory);
	    }

}
(3)SerializeUtil.java 序列化
package com.youlh.redis.cache;

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) {
	        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;
	    }
}


4 redis.properties
# Redis settings  
redis.host=127.0.0.1
redis.port=6379
redis.pass=

redis.maxIdle=1
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
redis.testWhileIdle=true
redis.minEvictableIdleTimeMillis=60000
redis.timeBetweenEvictionRunsMillis=30000
redis.numTestsPerEvictionRun=-1


##mybatis查询空间缓存时间,单位秒
com.youlh.mapper.DataVoyageMapper=3600
com.youlh.mapper.VoyageTimeTempMapper=3600
com.youlh.mapper.StoreCustomersMapper=3600
com.youlh.mapper.NoticeMapper=3600
com.youlh.mapper.HolidayMapper=3600



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值