---
title: "ibatis源码学习(五)缓存设计和实现"
author: "learnworld"
date: "2012-04-07T21:06:04Z"
tags: []
categories: ["开源软件"]
slug: "ibatis"
draft: false
lastmod: "2012-04-07T21:06:04Z"
id: 1478203
url: "https://learnworld.iteye.com/blog/1478203"
---

缓存不算是ibatis框架的一个亮点，但理解ibatis的缓存设计和实现对我们合理使用ibatis缓存是很有帮助的。本文将深入分析ibatis框架的缓存设计和实现。缓存的使用参见官方文档:[Cache Models](http://ibatis.apache.org/docs/dotnet/datamapper/ch03s08.html)。本文使用的ibatis版本为<span style="color:red">2.3.4</span>。

**问题**
在介绍ibatis缓存设计和实现之前，我们先思考几个问题。
1. 缓存的目标是什么？ 缓存中存放哪些数据？
2. 缓存数据的生命周期是怎样？ 何时创建？ 何时更新？ 何时清理？
3. 缓存数据的作用域是怎样？ Session？ 应用范围？
4. 有哪些缓存管理策略？ 如何加载策略配置？ 如何使用这些策略？
5. 缓存key的生成由哪些因素决定？
如果你能轻松回答上面这些问题，恭喜，你没有继续看下去的必要了 :D ，本文将围绕这些问题分析ibatis缓存的设计和实现。

**核心类图**
缓存相关的核心如下:
![](http://dl.iteye.com/upload/attachment/0066/1593/86c07f49-2309-396d-96e0-50b5e9756f4b.jpg)
**1. CacheModel**
ibatis缓存的核心类，代表一个缓存对象，内部包含该缓存的配置信息(刷新间隔、缓存管理策略等)。该类和配置文件中的<cacheModel>标签对应。每个CacheModel内部组合一个CacheController对象，用于维护缓存数据。

**2. CacheController**
该接口表示采用某种策略的缓存管理者，缓存数据实际维护在CacheController实现类中。ibatis框架默认提供了四种缓存管理策略:MemoryCacheController提供了基于reference类型的管理策略；FifoCacheController提供了"先进先出"方式的管理策略；LruCacheController提供了"近期最少使用"的管理策略；OSCacheController提供了基于OSCache2.0缓存的管理策略。每种策略的实现方式将在下文介绍。

**3. ExecuteListener**
该接口表示一个观察者，它的唯一实现类是CacheModel。将该观察者注册到某个MappedStatement对象中，目的是当MappedStatement执行时，通知ExecuteListener执行相应操作(清除缓存对象)。该接口用于实现<flushOnExecute>这个功能。

**4. MappedStatement**
该类表示sql语句信息和执行时相关上下文环境。其内部包含List属性executeListeners，表示在sql执行后需要通知的观察者列表。

**5. CachingStatement**
该类是MappedStatement的包装类，用于sql执行时增加缓存功能。在配置文件中指定cacheModel属性的sql statement初始化时都会被包装成该对象。

**示例**
下面以常见的ibaits缓存配置举例，说明缓存的实现过程。

```java
    <cacheModel id="CATEGORY-CACHE" type="Memory" serialize="false" readOnly="true">
        <property name="reference-type" value="WEAK" />
        <flushInterval minutes="15" />
        <flushOnExecute statement="MS-UPDATE-CATEGORY" />
    </cacheModel>

    <select id="MS-FIND-SUB-CATEGORY" resultMap="RM-PF-PIC-CATEGORY"
        parameterClass="java.lang.Integer"  cacheModel="CATEGORY-CACHE">
        select id,cat_name,parent_id,is_leaf,prohibit_flag 
        from PF_PIC_CATEGORY
        where parent_id=#parentId#
    </select>

    <update id="MS-UPDATE-CATEGORY" parameterClass="TA-PF-PIC-CATEGORY">
        update PF_PIC_CATEGORY 
        set cat_name=#catName#,gmt_modified=now()
        where id=#id#
    </update>
```

上述配置文件作用如下： 为MS-FIND-SUB-CATEGORY这条语句定义了名为CATEGORY-CACHE的Cache对象，采用基于内存(reference类型为弱引用)的缓存管理策略，缓存默认刷新时间为15min； 当执行MS-UPDATE-CATEGORY语句时，清除CATEGORY-CACHE缓存对象。

**初始化过程**
缓存初始化的主要过程有以下三点:
**1. 解析cacheModel配置，生成cacheModel对象。**该功能由SqlMapParser完成(初始化和配置文件解析参见[该文](http://learnworld.iteye.com/blog/1450057))，部分源码如下:

```java
public class SqlMapParser {
  private void addCacheModelNodelets() {
    parser.addNodelet("/sqlMap/cacheModel", new Nodelet() {
      public void process(Node node) throws Exception {
        Properties attributes = NodeletUtils.parseAttributes(node, state.getGlobalProps());
        //解析各属性值
        String id = state.applyNamespace(attributes.getProperty("id"));
        String type = attributes.getProperty("type");
        String readOnlyAttr = attributes.getProperty("readOnly");
        Boolean readOnly = readOnlyAttr == null || readOnlyAttr.length() <= 0 ? null : new Boolean("true".equals(readOnlyAttr));
        String serializeAttr = attributes.getProperty("serialize");
        ...
        // 生成CacheModelConfig对象
        CacheModelConfig cacheConfig = state.getConfig().newCacheModelConfig(id, (CacheController) Resources.instantiate(clazz), readOnly.booleanValue(), serialize.booleanValue());
        state.setCacheConfig(cacheConfig);
      }
    });
    ... 
  }
}
```

上面的addCacheModelNodelets()方法目标是解析缓存相关配置信息，生成CacheModelConfig对象，CacheModelConfig构造过程中会生成cacheModel对象，最终cacheModel对象统一维护在SqlMapExecutorDelegate.cacheModels这个map属性中。

**2. 为配置cacheModel属性的sql语句生成CachingStatement对象。**该过程在SqlStatementParser中完成，部分源码如下:

```java
public class SqlStatementParser {
  public void parseGeneralStatement(Node node, MappedStatement statement) {
    ...
    String cacheModelName = state.applyNamespace(attributes.getProperty("cacheModel"));
    ...
    //下面这段代码在MappedStatementConfig的构造方法中，这里为了方便说明
    if (cacheModelName != null && cacheModelName.length() > 0 && client.getDelegate().isCacheModelsEnabled()) {
      //获取上面生成的cacheModel对象
      CacheModel cacheModel = client.getDelegate().getCacheModel(cacheModelName);
      //生成包装者对象
      mappedStatement = new CachingStatement(statement, cacheModel);
    } else {
      mappedStatement = statement;
    }
    ...
  }
}
```


**3. 将cacheModel这个观察者注册到其flushOnExecute属性对应的statement中**，目的是statement执行后可以通知cacheModel清除缓存。 该过程由SqlMapConfigParser.addSqlMapConfigNodelets()方法实现，最终调用SqlMapConfiguration.wireUpCacheModels()方法。部分源码如下:

```java
public class SqlMapConfiguration{
  private void wireUpCacheModels() {
    // 循环处理每一个cacheModel
    Iterator cacheNames = client.getDelegate().getCacheModelNames();
    while (cacheNames.hasNext()) {
      String cacheName = (String) cacheNames.next();
      CacheModel cacheModel = client.getDelegate().getCacheModel(cacheName);
      //获取cacheModel对应的flushTriggerStatement，由<flushOnExecute>配置
      Iterator statementNames = cacheModel.getFlushTriggerStatementNames();
      while (statementNames.hasNext()) {
        String statementName = (String) statementNames.next();
        MappedStatement statement = client.getDelegate().getMappedStatement(statementName);
        if (statement != null) {
          //注册观察者
          statement.addExecuteListener(cacheModel);
        } else {
          throw new RuntimeException("Could not find statement named '" + statementName + "' for use as a flush trigger for the cache model named '" + cacheName + "'.");
        }
      }
    ...
    }
  }
}
```


**SQL执行过程**
已配置缓存的sql语句执行时，统一交由CachingStatement处理(sql完整执行过程参见[该文](http://learnworld.iteye.com/blog/1447284))，下面以单个对象查询为例，通过源码说明使用缓存后的SQL执行过程。

1. CachingStatement.executeQueryForObject()方法用于处理单个对象的查询请求，部分源码如下:

```java
  public Object executeQueryForObject(StatementScope statementScope, Transaction trans, Object parameterObject, Object resultObject)
      throws SQLException {
    //获取CacheKey
    CacheKey cacheKey = getCacheKey(statementScope, parameterObject);
    cacheKey.update("executeQueryForObject");
    //根据cacheKey查询缓存value
    Object object = cacheModel.getObject(cacheKey);
    if (object == CacheModel.NULL_OBJECT){
    	//已缓存，值为null
    	object = null;
    }else if (object == null) {
        //没有缓存，通过组合的statement查询
       object = statement.executeQueryForObject(statementScope, trans, parameterObject, resultObject);
       //将查询结果放入缓存中
       cacheModel.putObject(cacheKey, object);
    }
    return object;
  }
```

上面的查询过程中，核心逻辑如下:
1. 根据参数对象生成cacheKey(该过程稍后再详细说明)；
2. 根据cacheKey从cacheModel中获取对应的缓存value。
2.1 如果为null，则通过组合的statement查询，并将查询结果放入缓存中。
2.2 如果不为null，则直接返回缓存value。
可以看出，缓存的查询和更新都是交由cacheModel对象完成，下面看一下cacheModel的查询和更新实现。

2. 通过cacheModel查询缓存的部分源码如下:

```java
  public Object getObject(CacheKey key) {
  	Object value = null;
    synchronized (this) {
      // 判断缓存对象有没有过期，如果过期则清除
      if (flushInterval != NO_FLUSH_INTERVAL
          && System.currentTimeMillis() - lastFlush > flushInterval) {
        flush();
      }

      // 通过controller查询缓存value
      value = controller.getObject(this, key);
      // 如果设置readOnly=false, serialize=true，需要反序列化缓存value
      if (serialize && !readOnly &&
       	    (value != NULL_OBJECT && value != null)) {
        try {
          ByteArrayInputStream bis = new ByteArrayInputStream((byte[]) value);
          ObjectInputStream ois = new ObjectInputStream(bis);
          value = ois.readObject();
          ois.close();
        } catch (Exception e) {
          ...
        }
      }
      ...
    return value;
  }
```

首先根据配置的flushInterval值判断缓存value有没有过期，如果过期则清除缓存；接着从controller中获取缓存value；如果存储的value是经过序列化的，这里需要再反序列化。

3. 通过cacheModel更新缓存的部分源码如下:

```java
  public void putObject(CacheKey key, Object value) {
  	if (null == value) value = NULL_OBJECT;
  	synchronized ( this )  {
      // 如果设置readOnly=false, serialize=true，需要序列化缓存value
      if (serialize && !readOnly && value != NULL_OBJECT) {
        try {
          ByteArrayOutputStream bos = new ByteArrayOutputStream();
          ObjectOutputStream oos = new ObjectOutputStream(bos);
          oos.writeObject(value);
          oos.flush();
          oos.close();
          value = bos.toByteArray();
        } catch (IOException e) {
          ...
        }
      }
      // 通过controller更新缓存
      controller.putObject(this, key, value);
      ...
    }
  } 
```

cacheModel更新缓存时，先判断缓存value是否需要序列化，如果需要则执行序列化操作；最后通过controller更新缓存value。

**小结**
从上面的查询过程可以看出，ibatis缓存查询和更新都是交由cacheModel完成，cacheModel承担缓存管理者的角色，如判断缓存是否过期等；最终统一交由controller完成。

**缓存管理策略**
在上文的核心类图说明时，我们提到了ibatis默认有四种缓存管理策略，下面分别看一下这四个controller的实现。
**1. MemoryCacheController**

```java
public class MemoryCacheController implements CacheController {
  private MemoryCacheLevel cacheLevel = MemoryCacheLevel.WEAK;
  private Map cache = Collections.synchronizedMap(new HashMap());

  public void putObject(CacheModel cacheModel, Object key, Object value) {
    Object reference = null;
    //弱引用
    if (cacheLevel.equals(MemoryCacheLevel.WEAK)) {
      reference = new WeakReference(value);
    //软应用
    } else if (cacheLevel.equals(MemoryCacheLevel.SOFT)) {
      reference = new SoftReference(value);
    //强引用
    } else if (cacheLevel.equals(MemoryCacheLevel.STRONG)) {
      reference = new StrongReference(value);
    }
    cache.put(key, reference);
  }

  public Object getObject(CacheModel cacheModel, Object key) {
    Object value = null;
    Object ref = cache.get(key);
    if (ref != null) {
      if (ref instanceof StrongReference) {
        value = ((StrongReference) ref).get();
      } else if (ref instanceof SoftReference) {
        value = ((SoftReference) ref).get();
      } else if (ref instanceof WeakReference) {
        value = ((WeakReference) ref).get();
      }
    }
    return value;
  }
}
```

MemoryCacheController使用reference类型来管理cache行为，垃圾收集器可以通过配置的reference类型（强引用、弱应用、软应用）判断是否要回收cache中的数据。

**2. FifoCacheController**

```java
public class FifoCacheController implements CacheController {
  private int cacheSize;  // 缓存大小
  private Map cache;   // 缓存实际存储对象
  private List keyList;  //链表，用于控制key顺序

  public void putObject(CacheModel cacheModel, Object key, Object value) {
    cache.put(key, value);
    keyList.add(key);
    // 超过缓存最大值的处理策略
    if (keyList.size() > cacheSize) {
      try {
        //清除最先进来的key
        Object oldestKey = keyList.remove(0);
        cache.remove(oldestKey);
      } catch (IndexOutOfBoundsException e) {
        ...
      }
    }
  }

  public Object getObject(CacheModel cacheModel, Object key) {
    return cache.get(key);
  }
}
```

FifoCacheController使用先进先出的缓存管理策略，通过内部维护的链表控制key的先后顺序。当缓存超出预定大小后，清除链表头部元素对应的value。

**3. LruCacheController**

```java
public class LruCacheController implements CacheController {
  private int cacheSize;  // 缓存大小
  private Map cache;   // 缓存实际存储对象
  private List keyList;  //链表，用于控制key顺序
  public void putObject(CacheModel cacheModel, Object key, Object value) {
    cache.put(key, value);
    keyList.add(key);
    if (keyList.size() > cacheSize) {
      try {
        Object oldestKey = keyList.remove(0);
        cache.remove(oldestKey);
      } catch (IndexOutOfBoundsException e) {
        //ignore
      }
    }
  }

  public Object getObject(CacheModel cacheModel, Object key) {
    Object result = cache.get(key);
    // 每次查询后，将key移到List的尾部
    keyList.remove(key);
    if (result != null) {
      keyList.add(key);
    }
    return result;
  }
}
```

LruCacheController采用近期最少使用的缓存管理策略，实现上和FifoCacheController类似，唯一的差别是查询时将当前key移到keyList的尾部，保证经常查询的key都在链表的尾部，最少使用的key都在链表的头部。 当缓存超出预定大小后，直接清除链表头部元素对应的value即可。

**4. OSCacheController**

```java
public class OSCacheController implements CacheController {
  private static final GeneralCacheAdministrator CACHE = new GeneralCacheAdministrator();
  public Object getObject(CacheModel cacheModel, Object key) {
    String keyString = key.toString();
    try {
      int refreshPeriod = (int) (cacheModel.getFlushIntervalSeconds());
      return CACHE.getFromCache(keyString, refreshPeriod);
    } catch (NeedsRefreshException e) {
      CACHE.cancelUpdate(keyString);
      return null;
    }
  }
  
  public void putObject(CacheModel cacheModel, Object key, Object object) {
    String keyString = key.toString();
    CACHE.putInCache(keyString, object, new String[]{cacheModel.getId()});
  }
}
```

OSCacheController采用OSCache2.0管理缓存，这里只是OSCache2.0缓存引擎的一个Plugin。我们可以借鉴OSCacheController的实现方式，实现自定义缓存实现，实现方式可以参考: [ibatis-with-memcached](https://code.google.com/p/ibatis-with-memcached/)。

**cacheKey生成策略**
上文的SQL执行过程中，查询缓存时首先需要根据参数对象生成cacheKey，再根据cacheKey在缓存中查找。核心实现源码如下:

```java
  public CacheKey getCacheKey(StatementScope statementScope, Object parameterObject) {
    //生成CacheKey
    CacheKey key = statement.getCacheKey(statementScope, parameterObject);
    if (!cacheModel.isReadOnly() && !cacheModel.isSerialize()) {
      //更新CacheKey
      key.update(statementScope.getSession());
    }
    return key;
  }
```

其中MappedStatement.getCacheKey()实现如下:

```java
  public CacheKey getCacheKey(StatementScope statementScope, Object parameterObject) {
    Sql sql = statementScope.getSql();
    ParameterMap pmap = sql.getParameterMap(statementScope, parameterObject);
    CacheKey cacheKey = pmap.getCacheKey(statementScope, parameterObject);
    cacheKey.update(id);
    cacheKey.update(baseCacheKey);
    cacheKey.update(sql.getSql(statementScope, parameterObject));
    return cacheKey;
  }
```

从上面过程可以看出，cacheKey的生成由以下几个元素决定:
1) 参与参数映射的参数值
2) statement id
3) baseCacheKey
4) sql语句
5) 执行方法名称
当设置缓存类型为读写缓存且未序列化时，session值也参与cacheKey的生成。
从cacheKey的生成策略可以看出，当缓存类型是只读时，缓存数据在应用范围内共享；当缓存类型为读写缓存且未序列化时，缓存数据的作用域下降到session范围，要尽量避免这种情况发生。

**总结**
从设计上看，ibatis缓存设计主要涉及以下三种模式：
**策略模式：** 默认提供四种不同的缓存管理策略，可以通过配置文件指定使用的策略，查询缓存时由CacheModel调用对应策略的Controller。
**观察者模式：** 该模式主要针对配置<flushOnExecute>的缓存清除。在初始化时向目标statement注册观察者；当statement执行完毕后，会通知观察者清除缓存。
**包装者模式：** CachingStatement通过包装MappedStatement对象，增加缓存实现，实现功能增强。

从ibatis缓存设计上看，如果sql传入的参数变化很多，或结果集数据量非常庞大，不适合使用ibatis缓存，可以考虑使用其他分布式缓存替代；对于参数比较稳定，结果集比较小的场景，可以考虑使用ibatis缓存，配置和使用上简洁方便。

ps. 如果你看到了这里，可以尝试回答一下本文开头的问题， :D