使用redis做mybatis的二级缓存

mybatis-config.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="cacheEnabled" value="true"/>
	</settings>
	
	<typeAliases>
		<package name="com.briup.bean" />
	</typeAliases>
	
	<!-- environments标签改为在spring中的数据源里面配置 -->
	
	<mappers>
		<mapper resource="com/briup/dao/IUserDaoMapper.xml"/>
	</mappers>
</configuration>  

实体类的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.briup.dao.IUserDao">
	
	<cache type="com.briup.cache.MybatisRedisCache"></cache>
	<insert id="saveUser" parameterType="User">
		<selectKey resultType="long" keyProperty="id" order="BEFORE">
			select my_seq.nextval from dual
		</selectKey>
		insert into t_user(id,name,age,dob) 
		values(#{id},#{name},#{age},#{dob})
	</insert>
	
	<select id="findAllUsers" resultType="User">
		select id,name,age,dob
		from t_user
	</select>
	
	<select id="findUserByName" parameterType="string" resultType="User">
		select id,name,age,dob
		from t_user
		where name=#{name}
	</select>
	
</mapper>

redis工具类

package com.briup.util;

import java.util.ResourceBundle;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisUtils {
	public static JedisPool jedisPool;

	static {
		//ResourceBundle会查找classpath下的xxx.properties的文件,xxx是方法中指定的
		ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");
		int maxTotal = Integer.parseInt(resourceBundle.getString("redis.pool.maxTotal"));
		int maxIdle = Integer.parseInt(resourceBundle.getString("redis.pool.maxIdle"));
		int maxWait = Integer.parseInt(resourceBundle.getString("redis.pool.maxWait"));
		String ip = resourceBundle.getString("redis.ip");
		int port = Integer.parseInt(resourceBundle.getString("redis.port"));

		JedisPoolConfig config = new JedisPoolConfig();
		// 设置最大连接数
		config.setMaxTotal(maxTotal);
		// 设置最大空闲数
		config.setMaxIdle(maxIdle);
		// 设置超时时间
		config.setMaxWaitMillis(maxWait);
		// 初始化连接池
		jedisPool = new JedisPool(config, ip, port);

	}
	
	public static void set(Object key, Object value) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.set(SerializingUtils.serialize(key), SerializingUtils.serialize(value));
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jedis.close();
		}
	}

	
	public static Object get(Object key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] keyBytes = SerializingUtils.serialize(key);
			if(jedis.exists(keyBytes)){
				return SerializingUtils.deserialize(jedis.get(keyBytes));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jedis.close();
		}
		return null;
	}
	
	public static void del(Object key) {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.del(SerializingUtils.serialize(key));
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jedis.close();
		}
	}
	
	public static void clear() {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			jedis.flushDB();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jedis.close();
		}
	}
	public static int getSize() {
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			jedis.close();
		}
		return jedis.dbSize().intValue();
	}
	
	public static Jedis getResource(){
		return jedisPool.getResource();
	}
}

cache工具类

package com.briup.cache;

import java.util.concurrent.locks.ReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.apache.ibatis.cache.CacheException;

import com.briup.util.JedisUtils;

/**
 * Cache为缓存接口,给缓存供应商的SPI(Service Provider Interface)
 * Cache接口的实现类必须有一个具有String类型参数的构造方法,该参数作为实现类对象的id,对其进行唯一标识
 */
public class MybatisRedisCache implements Cache {

	private String id;

	public MybatisRedisCache(String id) {
		this.id = id;
	}

	/**
	 * 清空缓存
	 */
	@Override
	public void clear() {
		JedisUtils.clear();
	}

	/**
	 * 获取缓存对象的唯一标识
	 */
	@Override
	public String getId() {
		return this.id;
	}

	/**
	 * 从缓存对象中获取key对应的value
	 */
	@Override
	public Object getObject(Object key) {
		return JedisUtils.get(key);
	}

	/**
	 * 获取读写锁 可选的方法,从3.2.6起这个方法不再被框架核心调用 任何需要的锁,都必须由缓存供应商提供
	 */
	@Override
	public ReadWriteLock getReadWriteLock() {

		return null;
	}

	/**
	 * 获取缓存对象中存储的键/值对的数量 可选的方法,没有被框架核心调用
	 */
	@Override
	public int getSize() {
		return JedisUtils.getSize();
	}

	/**
	 * 保存key/value到缓存对象中 key可以是任何对象
	 */
	@Override
	public void putObject(Object key, Object value) {
		JedisUtils.set(key, value);
	}

	/**
	 * 可选的方法,没有被核心框架调用,移除key对应的value
	 */
	@Override
	public Object removeObject(Object key) {

		return null;
	}

	/**
	 * 重新equals方法
	 */
	@Override
	public boolean equals(Object o) {
		if (getId() == null)
			throw new CacheException("Cache instances require an ID.");
		if (this == o)
			return true;
		if (!(o instanceof Cache))
			return false;

		Cache otherCache = (Cache) o;
		return getId().equals(otherCache.getId());
	}

	/**
	 * 重新hashCode方法
	 */
	@Override
	public int hashCode() {
		if (getId() == null)
			throw new CacheException("Cache instances require an ID.");
		return getId().hashCode();
	}

}

序列化工具类

package com.briup.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializingUtils {
	
	public static byte[] serialize(Object obj) {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream out = null;
		try {
			bos = new ByteArrayOutputStream();
			out = new ObjectOutputStream(bos);
			out.writeObject(obj);
			out.flush();
		}
		catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(out!=null)out.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
		return bos.toByteArray();
	}
	
	public static Object deserialize(byte[] data) {
		ObjectInputStream in = null;
		Object obj = null;
		try {
			ByteArrayInputStream byteIn = new ByteArrayInputStream(data);
			in = new ObjectInputStream(byteIn);
			obj = in.readObject();
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(in!=null)in.close();
			}catch (IOException e) {
				e.printStackTrace();
			}
		}
		return obj;
	}
	
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值