RedisCluster实现mybatis的二级缓存

RedisCluster实现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 org.springframework.data.redis.connection.RedisClusterConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;
public class RedisCache implements Cache{
	private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

    private static JedisConnectionFactory jedisConnectionFactory;

    private final String id;

    /**
     * 读写锁  共享读、互斥写
     * ReentrantLock   可重入锁 
     * synchronized    同步锁   
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public RedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.debug("MybatisRedisCache:id=" + id);
        this.id = id;
    }

    public void clear()
    {
         RedisClusterConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getClusterConnection();
            //connection 就是一个jedis对象
           
            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)
    {
        Object result = null;
        RedisClusterConnection connection = null;
        try
        {
        	 connection = jedisConnectionFactory.getClusterConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            result = serializer.deserialize(connection.get(serializer.serialize(key)));
        }
        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;
        RedisClusterConnection connection = null;
        try
        {
        	connection = jedisConnectionFactory.getClusterConnection();
            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)
    {
    	 RedisClusterConnection connection = null;
        try
        {
        	connection = jedisConnectionFactory.getClusterConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    
    public Object removeObject(Object key)
    {
    	 RedisClusterConnection connection = null;
        Object result = null;
        try
        {
        	connection = jedisConnectionFactory.getClusterConnection();
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
            result =connection.expire(serializer.serialize(key), 0);
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

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


}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
public class CacheTransfer {
	@Autowired
	public void setJedisConnectionFactory(JedisConnectionFactory factory){
		RedisCache.setJedisConnectionFactory(factory);
	}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
	 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.2.xsd">
	<bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <constructor-arg index="0">

            <!-- RedisClusterConfiguration, -->
            <bean class="org.springframework.data.redis.connection.RedisClusterConfiguration">
                <constructor-arg>
                    <list>
                        <value>192.168.142.129:7000</value>
                        <value>192.168.142.129:7001</value>
                        <value>192.168.142.129:7002</value>
                        <value>192.168.142.129:7003</value>
                        <value>192.168.142.129:7004</value>
                        <value>192.168.142.129:7005</value>
                    </list>
                </constructor-arg>
                <property name="maxRedirects" value="5" />
            </bean>
            
            
        </constructor-arg>
        <constructor-arg index="1">
            <bean class="redis.clients.jedis.JedisPoolConfig">
                 <property name="maxTotal" value="100"/>
                 <property name="maxIdle" value="10"/>
                 <property name="minIdle" value="1"/>
                 <property name="maxWaitMillis" value="30000"/>
            </bean>
        </constructor-arg>
    </bean>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="redisConnectionFactory" />
    </bean>
    
    <bean id="cacheTransfer" class="com.*.*.*![在这里插入图片描述](https://img-blog.csdnimg.cn/20190510150800355.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ0MTA5ODk2,size_16,color_FFFFFF,t_70).CacheTransfer"></bean>
    

	</beans>
mybatis配置文件中开启二级缓存
<!-- 手动开启二级缓存 -->
<settings>
	<setting name="cacheEnabled" value="true"/>
<!--查询时,关闭关联对象即时加载以提高性能 -->
	<setting name="lazyLoadingEnabled" value="false"/>
</settings>

mapper.xml映射文件中开启二级缓存

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.*.*.*.CityMapper" >
<cache type="com.*.*.*.RedisCache"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值