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

来源:互联网 发布:挪威的森林披头士 知乎 编辑:程序博客网 时间:2024/06/02 07:28

  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 blocke.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 blocke.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 blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.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 blocke.printStackTrace();} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.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 blocke.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.1redis.port=6379redis.pass=redis.maxIdle=1redis.maxActive=600redis.maxWait=1000redis.testOnBorrow=trueredis.testWhileIdle=trueredis.minEvictableIdleTimeMillis=60000redis.timeBetweenEvictionRunsMillis=30000redis.numTestsPerEvictionRun=-1##mybatis查询空间缓存时间,单位秒com.youlh.mapper.DataVoyageMapper=3600com.youlh.mapper.VoyageTimeTempMapper=3600com.youlh.mapper.StoreCustomersMapper=3600com.youlh.mapper.NoticeMapper=3600com.youlh.mapper.HolidayMapper=3600


原创粉丝点击