七. Mybatis二级缓存

2019-10-13  本文已影响0人  任未然

概述

mybatis二级缓存是基于redis实现的,必须先配置好redis

一. 缓存类的实现

要想使用Mybatis的二级缓存,必须要实现Cache接口,具体的实现如下:

public class RedisCache implements Cache {

    private RedisTemplate<Object, Object> redisTemplate;

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private String id;

    public RedisCache(){}

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

    private RedisTemplate<Object, Object> getRedisTemplate() {
        if(null == this.redisTemplate) {
            this.redisTemplate = (RedisTemplate)ApplicationContextHolder.getBean("redisTemplate");
        }
        return this.redisTemplate;
    }

    @Override
    public String getId() {
        return this.id;
    }
    // 设置值
    @Override
    public void putObject(Object key, Object value) {
        if(value != null) {
            this.getRedisTemplate().opsForValue().set(key, value);
        }
    }
    //取值
    @Override
    public Object getObject(Object key) {
        if(null != key) {
            return this.getRedisTemplate().opsForValue().get(key);
        }
        return null;
    }
    //删除
    @Override
    public Object removeObject(Object key) {
        if(null != key) {
            this.getRedisTemplate().delete(key);
        }
        return null;
    }
    //清除所有
    @Override
    public void clear() {
        Set<Object> set = getRedisTemplate().keys("*:" + this.id + "*");
        if(null != set) {
            getRedisTemplate().delete(set);
        }
    }

    @Override
    public int getSize() {
        return 0;
    }
    //ReadWriteLock 读写锁。
    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}

获取ApplicationContext

@Component
public class ApplicationContextHolder implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}

mapper.xml配置

<!--
        如果想要对那些数据做缓存,就在这个文件中做如下配置
        flushInterval: 清空缓存的时间间隔,单位为毫秒; 默认情况是不设置,也就是没有刷新间隔,缓存仅仅调用更新语句时刷新。
        size: 可以被设置为任意正整数, 缓存的数量,默认是1024;
        evication: LRU 移除最长时间不被使用的对象。
        blocking: 默认是false;
     -->
<cache size="1024" type="com.qf.cache.RedisCache" />
上一篇下一篇

猜你喜欢

热点阅读