天天看點

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());
      }
    });
  }
           

繼續閱讀