Mybatis:整合Redis缓存
配置
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.util.CollectionUtils;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@Slf4j
public class MybatisRedisCache implements Cache {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
@Autowired
@Qualifier("redisTemplate3")
private RedisTemplate<String, Object> redisTemplate;
private String id;
public MybatisRedisCache(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 void putObject(Object key, Object value) {
if (redisTemplate == null) {
redisTemplate = (RedisTemplate<String, Object>) AppCtxUtils.getBean("redisTemplate3");
}
if (value != null) {
redisTemplate.opsForValue().set(key.toString(), value);
}
}
@Override
public Object getObject(Object key) {
try {
if (key != null) {
return redisTemplate.opsForValue().get(key.toString());
}
} catch (Exception e) {
log.error("缓存数据不存在 ");
}
return null;
}
@Override
public Object removeObject(Object key) {
if (key != null) {
redisTemplate.delete(key.toString());
}
return null;
}
@Override
public void clear() {
log.debug("清空缓存");
if (redisTemplate == null) {
redisTemplate = (RedisTemplate<String, Object>) AppCtxUtils.getBean("redisTemplate3");
}
Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
if (!CollectionUtils.isEmpty(keys)) {
redisTemplate.delete(keys);
}
}
@Override
public int getSize() {
Long size = redisTemplate.execute((RedisCallback<Long>) RedisServerCommands::dbSize);
return size.intValue();
}
@Override
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
}
工具类
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class AppCtxUtils implements ApplicationContextAware {
private static ApplicationContext appCtx;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
appCtx = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return appCtx.getBean(clazz);
}
public static <T> T getBean(String beanName) {
return (T) appCtx.getBean(beanName);
}
}
使用
import org.apache.ibatis.annotations.CacheNamespace;
@CacheNamespace(implementation= MybatisRedisCache.class,eviction= MybatisRedisCache.class)
public interface DemoMapper {
}