mybatis的redis缓存扩展库已经n久没有更新过了,最新的还是1.0.0-betal2 版本。
mybatis redis扩展存在很多问题,比如,他需要你单独配置redis的为他配置单独的redis配置信息,不支持集群,很挫,我们可以把他的RedisCache重写下,使用RedisTemplate来写,简化代码,增加可读性,与项目浑然一体统一配置
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
* @Title:
* @Description:
* @author: hollowJ
* @date: 2016/11/21
* @version: V1.0.0
*/
/**
* Cache adapter for Redis.
*
* @author Eduardo Macarron
*/
public final class RedisCache2 implements Cache {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private String id;
private RedisConnectionFactory redisConnectionFactory;
private RedisTemplate<String, Object> redisTemplate;
public RedisCache2(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
}
@Override
public String getId() {
return this.id;
}
@Override
public int getSize() {
return Integer.valueOf(getRedisTemplate().opsForHash().size(id).toString());
}
@Override
public void putObject(final Object key, final Object value) {
getRedisTemplate().opsForHash().put(id, key, value);
}
@Override
public Object getObject(final Object key) {
return getRedisTemplate().opsForHash().get(id, key);
}
@Override
public Object removeObject(final Object key) {
return getRedisTemplate().opsForHash().delete(id, key);
}
@Override
public void clear() {
getRedisTemplate().opsForHash().delete(id);
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
@Override
public String toString() {
return "Redis {" + id + "}";
}
private RedisTemplate<String, Object> getRedisTemplate() {
WebApplicationContext currentWebApplicationContext = ContextLoader.getCurrentWebApplicationContext();
return (RedisTemplate<String, Object>) currentWebApplicationContext.getBean("redisTemplate");
}
}