天天看点

MyBatis缓存五-MyBatis使用Redis缓存

作者:小雨在进步

MyBatis除了提供内置的一级缓存和二级缓存外,还支持使用第三方缓存(例如Redis、Ehcache)作为二级缓存。本节我们就来了解一下在MyBatis中如何使用Redis作为二级缓存以及它的实现原理。

MyBatis官方提供了一个mybatis-redis模块,该模块用于整合Redis作为二级缓存。使用该模块整合缓存,首先需要引入该模块的依赖,如果项目通过Maven构建,则只需要向pom.xml文件中添加如下内容:

<dependency>
            <groupId>org.mybatis.caches</groupId>
            <artifactId>mybatis-redis</artifactId>
            <version>1.0.0-beta2-SNAPSHOT</version>
        </dependency>           

然后需要在Mapper的XML配置文件中添加缓存配置,例如:

<cache type="org.mybatis.caches.redis.RedisCache" eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"
    >
        <property name="timeout" value="100"/>
    </cache>           

最后,需要在classpath下新增redis.properties文件,配置Redis的连接信息。下面是redis.properties配置案例:

redis.host=192.168.1.222
redis.port=6379
redis.password=G^liW20pnX8#q2!           

注意mybatis-redis模块项目地址:https://github.com/mybatis/redis-cache。接下来我们简单地了解一下mybatis-redis模块的实现。该模块提供了一个比较核心的缓存实现类,即RedisCache类。RedisCache实现了Cache接口,使用Jedis客户端操作Redis,在RedisCache构造方法中建立与Redis的连接,代码如下:

public RedisCache(final String id) {
    if (id == null) {
      throw new IllegalArgumentException("Cache instances require an ID");
    }
    this.id = id;
    // 通过RedisConfigurationBuilder对象,获取Redis配置信息
    redisConfig = RedisConfigurationBuilder.getInstance().parseConfiguration();
    // 实例化JedisPool,与Redis服务器建立连接
    pool = new JedisPool(redisConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getConnectionTimeout(),
        redisConfig.getSoTimeout(), redisConfig.getPassword(), redisConfig.getDatabase(), redisConfig.getClientName(),
        redisConfig.isSsl(), redisConfig.getSslSocketFactory(), redisConfig.getSslParameters(),
        redisConfig.getHostnameVerifier());
}           

在RedisCache构造方法中,首先获取RedisConfigurationBuilder对象,将redis.properties文件中的配置信息转换为RedisConfig对象,RedisConfig类是描述Redis配置信息的Java Bean。获取RedisConfig对象后,接着创建JedisPool对象,通过JedisPool对象与Redis服务器建立连接。

RedisCache使用Redis的Hash数据结构存放缓存数据。在RedisCache类的putObject()方法中,首先对Java对象进行序列化,mybatis-redis模块提供了两种序列化策略,即JDK内置的序列化机制和第三方序列化框架Kryo,具体使用哪种序列化方式,可以在redis.properties文件中配置。

对象序列化后,将序列化后的信息存放在Redis中。RedisCache类的putObject()方法实现如下:

public void putObject(final Object key, final Object value) {
    execute(new RedisCallback() {
        @Override
        public Object doWithRedis(Jedis jedis) {
            final byte[] idBytes = id.getBytes();
            jedis.hset(idBytes, key.toString().getBytes(), redisConfig.getSerializer().serialize(value));
            if (timeout != null && jedis.ttl(idBytes) == -1) {
                jedis.expire(idBytes, timeout);
            }
            return null;
        }
    });
}           

在RedisCache类的getObject()方法中,先根据Key获取序列化的对象信息,再进行反序列化操作,代码如下:

public Object getObject(final Object key) {
    return execute(new RedisCallback() {
      @Override
      public Object doWithRedis(Jedis jedis) {
        return redisConfig.getSerializer().unserialize(jedis.hget(id.getBytes(), key.toString().getBytes()));
      }
    });
  }           

需要注意的是,使用Redis作为二级缓存,需要通过<cache>标签的type属性指定缓存实现类为org.mybatis.caches.redis.RedisCache。MyBatis启动时会解析Mapper配置信息,为每个命名空间创建对应的RedisCache实例,由于JedisPool实例是RedisCache类的静态属性,因此JedisPool实例是所有RedisCache对象共享的。RedisCache的完整源码可参考mybatis-redis模块。

除了Redis外,MyBatis还提供了整合其他缓存的适配器。例如,ehcache-cache项目用于整合EhCache缓存,oscache-cache项目用于整合OSCache缓存,memcached-cache项目用于整合Memcached缓存。

这里有一个问题,redis资源是很昂贵的,最后怎么删除reids的数据。有种方式,一种是给数据设置有效期,还有一种是手动删除

1.设置有效期

<cache type="org.mybatis.caches.redis.RedisCache" eviction="FIFO"
        flushInterval="60000"
        size="512"
        readOnly="true"
    >
        <property name="timeout" value="100"/>
    </cache>           

在标签<cache> 属性timeout 设置值,这里的值就是redis的数据有效性,在解析<cache>时候的会创建RedisCache 实列,代码如下:

public Cache build() {
    setDefaultImplementations();
    Cache cache = newBaseCacheInstance(implementation, id);

    // 设置时间,如过期时间
    setCacheProperties(cache);
    // issue #352, do not apply decorators to custom caches
    if (PerpetualCache.class.equals(cache.getClass())) {
      for (Class<? extends Cache> decorator : decorators) {
        cache = newCacheDecoratorInstance(decorator, cache);
        setCacheProperties(cache);
      }
      cache = setStandardDecorators(cache);
    } else if (!LoggingCache.class.isAssignableFrom(cache.getClass())) {
      cache = new LoggingCache(cache);
    }
    return cache;
  }           

方法setCacheProperties 可以设置过期时间,这里返回的不是RedisCache,而是有LoggingCache装饰的,在执行查询的时候使用的也不是直接使用LoggingCache,而是用过TransactionalCacheManager的操作

TransactionalCache,代码如下:

public <E> List<E> query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
      throws SQLException {
    // 获取MappedStatement对象中维护的二级缓存对象
    Cache cache = ms.getCache();
    if (cache != null) {
      // 判断是否需要刷新二级缓存
      flushCacheIfRequired(ms);
      if (ms.isUseCache() && resultHandler == null) {
        ensureNoOutParams(ms, boundSql);
        // 从MappedStatement对象对应的二级缓存中获取数据
        @SuppressWarnings("unchecked")
        List<E> list = (List<E>) tcm.getObject(cache, key);
        if (list == null) {
          // 如果缓存数据不存在,则从数据库中查询数据
          list = delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
          // 將数据存放到MappedStatement对象对应的二级缓存中
          tcm.putObject(cache, key, list); // issue #578 and #116
        }
        return list;
      }
    }
    return delegate.<E> query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
  }           

List<E> list = (List<E>) tcm.getObject(cache, key);操作的是TransactionalCache,所以下面的 tcm.putObject(cache, key, list);代码不是把数据直接写到edis,写到TransactionalCache 中的entriesToAddOnCommit,类似于本地缓存。

那什么时候写入到redis中

需要执行sqlSession.commit(true); 代码如下

public void commit(boolean force) {
    try {
      executor.commit(isCommitOrRollbackRequired(force));
      dirty = false;
    } catch (Exception e) {
      throw ExceptionFactory.wrapException("Error committing transaction.  Cause: " + e, e);
    } finally {
      ErrorContext.instance().reset();
    }
  }           

这里调用的是CachingExecutor commit方法

public void commit(boolean required) throws SQLException {
    delegate.commit(required);
      // 执行写入操作
    tcm.commit();
  }           

TransactionalCacheManager的commit方法

public void commit() {
    for (TransactionalCache txCache : transactionalCaches.values()) {
      txCache.commit();
    }
  }           

TransactionalCache的commit方法

public void commit() {
    if (clearOnCommit) {
      delegate.clear();
    }
    flushPendingEntries();
    reset();
  }

  private void flushPendingEntries() {
    for (Map.Entry<Object, Object> entry : entriesToAddOnCommit.entrySet()) {
        // 写入reids
      delegate.putObject(entry.getKey(), entry.getValue());
    }
    for (Object entry : entriesMissedInCache) {
      if (!entriesToAddOnCommit.containsKey(entry)) {
        delegate.putObject(entry, null);
      }
    }
  }
           

这里的delegate指的是LoggingCache,再看LoggingCache 的dputObject方法

public void putObject(Object key, Object object) {
    delegate.putObject(key, object);
  }           

这个才是真正执行redisCache的putObject方法

2.手动删除

需要执行sqlSession.commit(true),过程和sqlSession.commit(true) 类似

最后执行的redisCache的rollback 方法

public Object removeObject(final Object key) {
    return execute(new RedisCallback() {
      @Override
      public Object doWithRedis(Jedis jedis) {
        return jedis.hdel(id, key.toString());
      }
    });
  }
           

继续阅读