欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

RedisCluster实现mybatis的二级缓存

程序员文章站 2022-04-13 17:43:14
...

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"/>
相关标签: mybatis二级缓存