Skip to content

Instantly share code, notes, and snippets.

@happy-tao
Last active August 29, 2015 14:20
Show Gist options
  • Save happy-tao/a91106d79abe24966c52 to your computer and use it in GitHub Desktop.
Save happy-tao/a91106d79abe24966c52 to your computer and use it in GitHub Desktop.
Redis作为MyBatis的二级缓存
<redis
host="127.0.0.1"
port="6379"
password="123456"
>
</redis>
package com.iit.core.redis;
import com.iit.core.util.SerializeUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 使用redis作为mybatis的二级缓存
* 参考了ehcache,https://github.com/mybatis/ehcache-cache/blob/master/src/main/java/org/mybatis/caches/ehcache/AbstractEhcacheCache.java
*
* Created by wurt on 2015/5/7.
*/
public class RedisCache implements Cache {
private static Logger logger = LoggerFactory.getLogger(RedisCache.class);
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private String id;
public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug("mybatis cache : id is {}", id);
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public int getSize() {
int result = 0;
boolean success = true;
Jedis client = RedisClient.getResource();
try {
result = NumberUtils.toInt(client.dbSize().toString());
} catch (Exception e) {
success = false;
if (client != null) {
RedisClient.returnBrokenResource(client);
}
} finally {
if (success) {
RedisClient.returnResource(client);
}
}
logger.debug("mybatis cache : get size is {}", result);
return result;
}
@Override
public void putObject(Object key, Object value) {
boolean success = true;
Jedis client = RedisClient.getResource();
try {
client.set(SerializeUtils.serialize(key), SerializeUtils.serialize(value));
} catch (Exception e) {
success = false;
if (client != null) {
RedisClient.returnBrokenResource(client);
}
} finally {
if (success) {
RedisClient.returnResource(client);
}
}
logger.debug("mybatis cache : put object : key is {}, value is {}", key, value);
}
@Override
public Object getObject(Object key) {
Object value = null;
boolean success = true;
Jedis client = RedisClient.getResource();
try {
value = SerializeUtils.unserialize(client.get(SerializeUtils.serialize(key)));
} catch (Exception e) {
success = false;
if (client != null) {
RedisClient.returnBrokenResource(client);
}
} finally {
if (success) {
RedisClient.returnResource(client);
}
}
logger.debug("mybatis cache : get object : key is {}, value is {}", key, value);
return value;
}
@Override
public Object removeObject(Object key) {
Object value = null;
boolean success = true;
Jedis client = RedisClient.getResource();
try {
value = client.expire(SerializeUtils.serialize(key), 0);
} catch (Exception e) {
success = false;
if (client != null) {
RedisClient.returnBrokenResource(client);
}
} finally {
if (success) {
RedisClient.returnResource(client);
}
}
logger.debug("mybatis cache : remove object : key is {}, value is {}", key, value);
return value;
}
@Override
public void clear() {
boolean success = true;
Jedis client = RedisClient.getResource();
try {
client.flushDB();
client.flushAll();
} catch (Exception e) {
success = false;
if (client != null) {
RedisClient.returnBrokenResource(client);
}
} finally {
if (success) {
RedisClient.returnResource(client);
}
}
logger.debug("mybatis cache : clear DB");
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
}
package com.iit.core.redis;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.w3c.dom.Element;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
/**
* Created by wurt on 2015/1/14.
*/
public class RedisClient {
/**
* 服务端地址
*/
private static String host = null;
/**
* 服务端端口号
*/
private static int port = Protocol.DEFAULT_PORT;
/**
* 密码
*/
private static String password = null;
private static JedisPool pool = null;
/**
* 初始化配置信息
*
* @param ele
*/
public static void parse(Element ele) {
if(ele == null)
return ;
host = ele.getAttribute("host");
String strPort = ele.getAttribute("port");
if(StringUtils.isNotBlank(strPort))
port = NumberUtils.toInt(strPort, port);
String pwd = ele.getAttribute("password");
if(StringUtils.isNotBlank(pwd))
password = pwd;
}
public static JedisPool getPool() {
if (pool != null) {
return pool;
}
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(6);
config.setMinIdle(0);
config.setMaxTotal(6);
config.setMinEvictableIdleTimeMillis(300000);
config.setSoftMinEvictableIdleTimeMillis(-1);
config.setNumTestsPerEvictionRun(3);
config.setTimeBetweenEvictionRunsMillis(60000);//一分钟
config.setMaxWaitMillis(15000);
pool = new JedisPool(config, host, port, 10000, password);
return pool;
}
public static Jedis getResource(){
return getPool().getResource();
}
public static void returnResource(Jedis jedis){
getPool().returnResource(jedis);
}
public static void returnBrokenResource(Jedis jedis) {
getPool().returnBrokenResource(jedis);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"classpath://mybatis-3-mapper.dtd">
<mapper namespace="com.iit.core.user.entity.User">
<cache type="com.iit.core.redis.RedisCache" />
<resultMap type="User" id="resultMap">
<id property="id" column="ID" jdbcType="BIGINT" />
<result property="name" column="NAME" jdbcType="VARCHAR" />
<result property="cnName" column="CN_NAME" jdbcType="VARCHAR" />
<result property="password" column="PASSWORD" jdbcType="VARCHAR" />
<result property="userStateValue" column="USER_STATE" jdbcType="TINYINT" />
<result property="mobilePhone" column="MOBILE_PHONE" jdbcType="VARCHAR" />
<result property="registerTime" column="REGISTER_TIME" jdbcType="TIMESTAMP" />
<result property="md5Key" column="MD5_KEY" jdbcType="VARCHAR" />
<result property="avator" column="AVATOR" jdbcType="VARCHAR" />
<result property="summary" column="SUMMARY" jdbcType="VARCHAR" />
</resultMap>
</mapper>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment