mybaits+redis实现二级缓存

          mybaits本身有一级缓存和二级缓存,一级缓存我这里不做赘述,因为作用不是特别明显。这次我们要用的是二级缓存,二级缓存的主要是借助第三方内存/服务。我这边选择的是redis作为第三方缓存。在使用本demo之前,需要童鞋们自己本机下载一个redis服务器,具体安装可以自行百度一下。好了,废话不多说,直接上代码,我会在上代码的过程中一步一步的介绍。

第一步:配置maven包(mybaits和redis的jar包),这个可以在maven中央库里面找到,也可以从我提供的代码中查看pom.xml

第二步:配置application.xml(添加redsi的缓存)


	

		
		
		classpath:jdbc.properties
		classpath:redis.properties
		
		
	

		  
           
           
           
           
           
          
         
         
         
         
         
         
           
         
         
         
           
           
           
           
           
         
         
         
         
         
            
       
	
	 
     
 
     
     
         
         
         
         
         
     
     
 	
        
        
            
        
        
            
        
     
    
    
    
         
     


第三步:创建RedisCacheTransfer类

/**
 * 
 */
package com.iuweb.common.util;

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

/**
 * 
  * 
  * @Description:使用第三方内存数据库Redis作为二级缓存
  * @author wangguan
  * @date 2018年5月21日 下午2:45:53
  * @versidescribeon v 1.0
 */
public class RedisCacheTransfer {
	
	 @Autowired
	    public void setconnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
	        RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
	    }


}


第四步:RedisCahe类

/**
 * 
 */
package com.iuweb.common.util;


import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.RedisConnection;
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;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


/**
 * 
  * 
  * @Description:创建中间类RedisCacheTransfer,完成RedisCache.jedisConnectionFactory的静态注入,静态注入中间类
  * @author wangguan
  * @date 2018年5月21日 下午2:51:17
  * @versidescribeon v 1.0
 */
public class RedisCache implements Cache
{
    //private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

    private static JedisConnectionFactory jedisConnectionFactory;

    private final String id;

    /**
     * The {@code ReadWriteLock}.
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

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

    @Override
    public void clear()
    {
        RedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            connection.flushDb();
            connection.flushAll();
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public String getId()
    {
        return this.id;
    }

    @Override
    public Object getObject(Object key)
    {
        Object result = null;
        RedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            result = serializer.deserialize(connection.get(serializer.serialize(key)));
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
        return result;
    }

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

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

    @Override
    public void putObject(Object key, Object value)
    {
        RedisConnection connection = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer serializer = new JdkSerializationRedisSerializer();
            connection.set(serializer.serialize(key), serializer.serialize(value));
        }
        catch (JedisConnectionException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (connection != null) {
                connection.close();
            }
        }
    }

    @Override
    public Object removeObject(Object key)
    {
        RedisConnection connection = null;
        Object result = null;
        try
        {
            connection = jedisConnectionFactory.getConnection();
            RedisSerializer 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;
    }

} 
  


以上对应redis基本配置完毕,后面是配置mybaits

第五步:依然在applicationContext.xml中配置mybaits



	
		
		  
		
		
		
		
		
			    
				
				    
					
					
				
			
		
	


第五步:在mybatis-config.xml中配置




	
	
		  
		  
		  
		  
		  
		  
		
		  
		 
	


基本配置项已经做好了。下面就开始进行具体的demo实验了。controller和service层我就不写了,没有什么变化。这里我贴出mapper.xml





    
    
        
        
        
        
    
    
    
      
    
    
	
	
	
	
	  insert into iu_workbook (Id,ClasssName,ClasssCode,ClasssParent,ClasssRemarks) values(18,#{classsname},#{classscode},#{classsparent},#{classsremarks});
	
	
	
	
 


运行一下,在后台的控制台就能看出效果了。

PS:提供运行的demo,是从自己的eclipse中copy出来的,另外项目中用到了redis,mysql。需要提前准备好。jdk环境是1.7的

https://download.csdn.net/download/qq_35515521/10435226


你可能感兴趣的:(redis,mybatis)