springboot中mybatis整合redis做二级缓存

mybatis shiro spring cache都有自己的缓存接口,要想让他们有缓存,只需要实现他们的缓存接口即可。

//mybatis的缓存接口
org.apache.ibatis.cache.Cache

//shiro的缓存接口
org.apache.shiro.cache.Cache
org.apache.shiro.cache.CacheManager

//spring cache的缓存接口
org.springframework.cache.Cache
org.springframework.cache.CacheManager

mybatis使用redis做二级缓存

引入redis依赖

<!--redis,使用JRedis作为连接池-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

mybatis开启二级缓存

  1. mybatis-config.xml文件中配置如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--开启二级缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
</configuration>
  1. 在需要使用缓存的mapper.xml文件中加入如下内容:
 <cache eviction="LRU"
           type="com.xx.mybatis.MybatisRedisCache"/>

MybatisRedisCache是实现了org.apache.ibatis.cache.Cache接口的。
3. 实现org.apache.ibatis.cache.Cache接口

/**
 * 使用redis给mybatis做二级缓存
 */
public class MybatisRedisCache implements Cache{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * 通过构造函数注入的,就是在mapper中配置的名称空间
     */
    private String id;

    private MyRedisHelper myRedisHelper;

    public MybatisRedisCache(String id) {
        if(StringUtils.isEmpty(id)){
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
        logger.debug("创建了mybatis缓存,缓存id = {}", id);
    }

    /**
     * @return The identifier of this cache
     */
    @Override
    public String getId() {
        return this.id;
    }

    /**
     * @param key   Can be any object but usually it is a CacheKey
     * @param value The result of a select.
     */
    @Override
    public void putObject(Object key, Object value) {
        this.getMyRedisHelper().set(key, value);
    }

    /**
     * @param key The key
     * @return The object stored in the cache.
     */
    @Override
    public Object getObject(Object key) {
        return this.getMyRedisHelper().get(key);
    }

    /**
     * As of 3.3.0 this method is only called during a rollback
     * for any previous value that was missing in the cache.
     * This lets any blocking cache to release the lock that
     * may have previously put on the key.
     * A blocking cache puts a lock when a value is null
     * and releases it when the value is back again.
     * This way other threads will wait for the value to be
     * available instead of hitting the database.
     *
     * @param key The key
     * @return Not used
     */
    @Override
    public Object removeObject(Object key) {
        return this.getMyRedisHelper().del(key);
    }

    /**
     * Clears this cache instance.
     */
    @Override
    public void clear() {
        this.getMyRedisHelper().clear();
    }

    /**
     * Optional. This method is not called by the core.
     *
     * @return The number of elements stored in the cache (not its capacity).
     */
    @Override
    public int getSize() {
        return 0;
    }

    /**
     * Optional. As of 3.2.6 this method is no longer called by the core.
     * <p>
     * Any locking needed by the cache must be provided internally by the cache provider.
     *
     * @return A ReadWriteLock
     */
    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    /**
     * 通过全局的ApplicationContext来获取MyRedisHelper对象
     */
    private MyRedisHelper getMyRedisHelper() {
        if(myRedisHelper == null){
            ApplicationContext applicationContext = MyApplicationContextHolder.getApplicationContext();
            myRedisHelper = applicationContext.getBean("myRedisHelper", MyRedisHelper.class);
        }
        return myRedisHelper;
    }


}


MyApplicationContextHolder是一个持有applicationContext的类,会在springboot程序入口的main方法中将applicationContext设置到MyApplicationContextHolder中。

/**
 * 持有一个ApplicationContext,在程序入口的main方法中设置的
 */
public class MyApplicationContextHolder{

    private static ApplicationContext applicationContext;

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        MyApplicationContextHolder.applicationContext = applicationContext;
    }
}


@SpringBootApplication
public class PileTestingBackupApplication {

    public static void main(String[] args) {
        try{
            ApplicationContext applicationContext = SpringApplication.run(PileTestingBackupApplication.class, args);
            MyApplicationContextHolder.setApplicationContext(applicationContext);
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

}


MyRedisHelper是一个简单的对redisTemplate封装的类

@Component
public class MyRedisHelper {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    public MyRedisHelper() {

    }

    public MyRedisHelper(RedisTemplate<Object, Object> redisTemplate){
        this.redisTemplate = redisTemplate;
    }

    public RedisTemplate<Object, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     */
    public void expire(Object key, long time){
        if(time > 0){
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    @SuppressWarnings("ConstantConditions")
    public long getExpire(Object key){
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    @SuppressWarnings("ConstantConditions")
    public boolean hasKey(Object key){
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除缓存
     * @param keys 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public Object del(Object ... keys){
        if(keys == null || keys.length == 0){
            return null;
        }
        if(keys.length == 1){
            return redisTemplate.delete(keys[0]);
        }else{
            return redisTemplate.delete(Arrays.asList(keys));
        }
    }

    /**
     * 清空当前数据库,总共有16个(0-15)
     */
    public void clear(){
        redisTemplate.execute(new RedisCallback<Object>() {
            /**
             * Gets called by {@link RedisTemplate} with an active Redis connection. Does not need to care about activating or
             * closing the connection or handling exceptions.
             *
             * @param connection active Redis connection
             * @return a result object or {@code null} if none
             * @throws DataAccessException
             */
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb();
                return null;
            }
        });
    }


    //=========================================================String===================================================
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(Object key){
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     */
    public void set(Object key,Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     */
    public void set(Object key,Object value,long time){
        if(time > 0){
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        }else{
            set(key, value);
        }
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return
     */
    @SuppressWarnings("ConstantConditions")
    public long incr(Object key, long delta){
        if(delta < 0){
            throw new RedisOperateException(ResultEnum.REDIS_INCREASE_LESS_THAN_ZERO.getCode(),
                    ResultEnum.REDIS_INCREASE_LESS_THAN_ZERO.getMsg());
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(小于0)
     * @return
     */
    @SuppressWarnings("ConstantConditions")
    public long decr(Object key, long delta){
        if(delta > 0){
            throw new RedisOperateException(ResultEnum.REDIS_DECREASE_GREATER_THAN_ZERO.getCode(),
                    ResultEnum.REDIS_DECREASE_GREATER_THAN_ZERO.getMsg());
        }
        return redisTemplate.opsForValue().decrement(key, delta);
    }

    //=======================================================Map========================================================
    /**
     * HashGet
     * @param key 键 不能为null
     * @param hashKey 项 不能为null
     * @return 值
     */
    public Object hget(Object key,Object hashKey){
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object,Object> hmget(Object key){
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     */
    public void hmset(Object key, Map<Object,Object> map){
        redisTemplate.opsForHash().putAll(key, map);
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     */
    public void hmset(Object key, Map<Object,Object> map, long time){
        redisTemplate.opsForHash().putAll(key, map);
        expire(key, time);
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param hashKey 项
     * @param hashValue 值
     */
    public void hset(Object key,Object hashKey,Object hashValue){
        redisTemplate.opsForHash().put(key, hashKey, hashValue);
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param hashKey 项
     * @param hashValue 值
     * @param time 时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     */
    public void hset(Object key,Object hashKey,Object hashValue,long time){
        redisTemplate.opsForHash().put(key, hashKey, hashValue);
        expire(key, time);
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param hashKeys 项 可以使多个 不能为null
     */
    public void hdel(Object key, Object... hashKeys){
        redisTemplate.opsForHash().delete(key, hashKeys);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param hashKey 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(Object key, Object hashKey){
        return redisTemplate.opsForHash().hasKey(key, hashKey);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key 键
     * @param hashKey 项
     * @param by 要增加几(大于0)
     * @return
     */
    public double hincr(Object key, Object hashKey,double by){
        if(by < 0){
            throw new RedisOperateException(ResultEnum.REDIS_INCREASE_LESS_THAN_ZERO.getCode(),
                    ResultEnum.REDIS_INCREASE_LESS_THAN_ZERO.getMsg());
        }
        return redisTemplate.opsForHash().increment(key, hashKey, by);
    }

    /**
     * hash递减
     * @param key 键
     * @param hashKey 项
     * @param by 要减少记(小于0)
     * @return
     */
    public double hdecr(Object key, Object hashKey,double by){
        if(by > 0){
            throw new RedisOperateException(ResultEnum.REDIS_DECREASE_GREATER_THAN_ZERO.getCode(),
                    ResultEnum.REDIS_DECREASE_GREATER_THAN_ZERO.getMsg());
        }
        return redisTemplate.opsForHash().increment(key, hashKey, -1.0 * by);
    }

    //============================================ set =============================================
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> sGet(Object key){
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    @SuppressWarnings("ConstantConditions")
    public boolean sHasKey(Object key, Object value){
        return redisTemplate.opsForSet().isMember(key, value);
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    @SuppressWarnings("ConstantConditions")
    public long sSet(Object key, Object...values){
        return redisTemplate.opsForSet().add(key, values);
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    @SuppressWarnings("ConstantConditions")
    public long sSetAndTime(Object key,long time,Object...values){
        long res = redisTemplate.opsForSet().add(key, values);
        expire(key, time);
        return res;
    }


    /**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
    @SuppressWarnings("ConstantConditions")
    public long sGetSetSize(Object key){
        return redisTemplate.opsForSet().size(key);
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    @SuppressWarnings("ConstantConditions")
    public long setRemove(Object key, Object ...values){
        return redisTemplate.opsForSet().remove(key, values);
    }

    //================================================list==================================================

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(Object key, long start, long end){
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
    @SuppressWarnings("ConstantConditions")
    public long lGetListSize(Object key){
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(Object key,long index){
        return redisTemplate.opsForList().index(key, index);
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     */
    public void lSet(Object key, Object value){
        redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     */
    public void lSet(Object key, Object value, long time){
        lSet(key, value);
        expire(key, time);
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param values 值
     * @return
     */
    public void lSet(Object key, List<Object> values){
        redisTemplate.opsForList().rightPushAll(key, values);
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param values 值
     * @param time 时间(秒)
     * @return
     */
    public void lSet(Object key, List<Object> values, long time){
        lSet(key, values);
        expire(key, time);
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     */
    public void lUpdateIndex(Object key, long index,Object value){
        redisTemplate.opsForList().set(key, index, value);
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    @SuppressWarnings("ConstantConditions")
    public long lRemove(Object key, long count, Object value){
        return redisTemplate.opsForList().remove(key, count, value);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值