1. 在 *Mapper.xml 内添加 cache 标签,type的值为自定义的redisCache类的全路径
2. 定义RedisCache类,继承自Cache,如下:
public class RedisCache implements Cache {
private RedisTemplate redisTemplate;
private final String id;
public RedisCache(String id){
this.id = id;
}
@Override
public String getId() {
return id;
}
@Override
public void putObject(Object o, Object o1) {
if(o == null) return ;
if(redisTemplate == null)
redisTemplate = ((RedisTemplate) ApplicationContextUtil.getBean("redisTemplate"));
redisTemplate.opsForHash().put(id,o.toString(),o1);
}
@Override
public Object getObject(Object o) {
if(o == null) return null;
if(redisTemplate == null)
redisTemplate = ((RedisTemplate) ApplicationContextUtil.getBean("redisTemplate"));
return redisTemplate.opsForHash().get(id,o.toString());
}
// 为mybatis的保留方法,基本不使用
@Override
public Object removeObject(Object o) {
return null;
}
//delete,save,update都会调用这个方法
@Override
public void clear() {
if(redisTemplate == null)
redisTemplate = ((RedisTemplate) ApplicationContextUtil.getBean("redisTemplate"));
redisTemplate.delete(id);
}
@Override
public int getSize() {
if(redisTemplate == null)
redisTemplate = ((RedisTemplate) ApplicationContextUtil.getBean("redisTemplate"));
return redisTemplate.opsForHash().size(id).intValue();
}
}
原文:https://www.cnblogs.com/c21w/p/15354529.html