一、一级缓存源码解析
注意:看mybatis-3-master模块中的代码即可。
一级缓存到底是什么?一级缓存什么时候被创建、一级缓存的工作流程是怎样的?相信你现在应该会有这几个疑问,那么我们本节就来研究一下一级缓存的本质。
1 缓存位置
一级缓存就绕不开SqlSession,Alt+7 查看SqlSession中关于缓存的方法。
经过定位发现字面上只有 clearCache() 和缓存有关,因为其有父子关系,直接查看下方流程图。
PerpetualCache中一级缓存相关的部分代码
public class PerpetualCache implements Cache {/*** 缓存容器*/private Map<Object, Object> cache = new HashMap<>();@Overridepublic void clear() {cache.clear();}}
由上可知一级缓存只是本地存储的 Map容器。
2 缓存的创建-createCacheKey
执行器Executor执行具体的查询,其缓存的创建应该也是来自Executor。Alt+7 定位到和缓存有关的方法createCacheKey,下面是BaseExecutor中createCacheKey的部分代码。
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject,RowBounds rowBounds, BoundSql boundSql) {CacheKey cacheKey = new CacheKey();//MappedStatement 的 id// id就是Sql语句的所在位置 包名+类名+SQL名称cacheKey.update(ms.getId());// offset 就 是 0 ,rowBounds是分页参数cacheKey.update(rowBounds.getOffset());// limit 就 是 Integer.MAXVALUEcacheKey.update(rowBounds.getLimit());//具体的SQL语句cacheKey.update(boundSql.getSql());//后面是update 了 sql中带的参数cacheKey.update(value);...if (configuration.getEnvironment() != null) {// issue #176cacheKey.update(configuration.getEnvironment().getId());}return cacheKey;}
创建缓存key会经过一系列的update方法,udate方法由一个CacheKey这个对象来执行的,这个update方法最终由updateList的list来把五个值存进去,对照上面的代码和下面的图示,你应该能 理解这五个值都是什么了
这里需要注意一下最后一个值,configuration.getEnvironment().getId()这是什么,这其实就是 定义在mybatis-config.xml中的标签,见如下。
<environments default="development"><environment id="development"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="${jdbc.driver}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></dataSource></environment></environments>
3 缓存的使用
sqlSesssion执行查询时,会先从一级缓存中查询,查不到时再从数据库查询。从自定义持久层框架中,我们可以知道具体的查询是由Executor#query方法来执行的,可以从这个方法来分析缓存的使用。
Executor#query的部分代码:
@Override
public <E> List<E> query(MappedStatement ms, Object parameter,
RowBounds rowBounds, ResultHandler resultHandler)
throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameter);
//创建缓存
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
@SuppressWarnings("unchecked")
@Override
public <E> List<E> query(MappedStatement ms, Object parameter,
RowBounds rowBounds, ResultHandler resultHandler,
CacheKey key, BoundSql boundSql) throws SQLException {
...
// 根据key从缓存中获取结果
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
// 缓存中有数据
if (list != null) {
//这个主要是处理存储过程用的。
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
// 缓存中无数据,从数据库中查询。
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
...
}
// 从数据库中读取操作
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter,
RowBounds rowBounds, ResultHandler resultHandler,
CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
// 在缓存中,添加占位对象。此处的占位符,和延迟加载有关,可见 `DeferredLoad#canLoad()` 方法
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
// 执行读操作
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
// 从缓存中,移除占位对象
localCache.removeObject(key);
}
// 添加到缓存中 localCache = org.apache.ibatis.cache.impl.PerpetualCache
localCache.putObject(key, list);
// 暂时忽略,存储过程相关
if (ms.getStatementType() == StatementType.CALLABLE) {
// localOutputParameterCache = org.apache.ibatis.cache.impl.PerpetualCache
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
如果查不到的话,就从数据库查,在queryFromDatabase中,会对localcache进行写入。 localcache对象的put方法最终交给Map进行存放。
private Map<Object, Object> cache = new HashMap<Object, Object>();
@Override
public void putObject(Object key, Object value) {
cache.put(key, value);
}
二、mybatis-redis二级缓存源码剖析
RedisCache和大家普遍实现Mybatis的缓存方案大同小异,无非是实现Cache接口,并使用jedis操作缓存;不过该项目在设计细节上有一些区别;
1 RedisCache的创建
public final class RedisCache implements Cache {
public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require anID");
}
this.id = id;
RedisConfig redisConfig = RedisConfigurationBuilder.getInstance()
.parseConfiguration();
pool = new JedisPool(redisConfig, redisConfig.getHost(),
redisConfig.getPort(), redisConfig.getConnectionTimeout(),
redisConfig.getSoTimeout(),redisConfig.getPassword(),
redisConfig.getDatabase(), redisConfig.getClientName());
}
}
RedisCache在mybatis启动的时候,由MyBatis的CacheBuilder创建,创建的方式很简单,就是调用RedisCache的带有String参数的构造方法,即RedisCache(String id);而在RedisCache的构造方法中, 调用了 RedisConfigurationBuilder 来创建 RedisConfig 对象,并使用 RedisConfig 来创建JedisPool。
2 RedisConfig配置类
RedisConfig类继承了 JedisPoolConfig,并提供了 host,port等属性的包装,简单看一下RedisConfig的属性:
public class RedisConfig extends JedisPoolConfig {
private String host = Protocol.DEFAULT_HOST;
private int port = Protocol.DEFAULT_PORT;
private int connectionTimeout = Protocol.DEFAULT_TIMEOUT;
private int soTimeout = Protocol.DEFAULT_TIMEOUT;
private String password;
private int database = Protocol.DEFAULT_DATABASE;
private String clientName;
}
RedisConfig对象是由RedisConfigurationBuilder创建的,简单看下这个类的主要方法:
public RedisConfig parseConfiguration(ClassLoader classLoader) {
Properties config = new Properties();
InputStream input = classLoader.getResourceAsStream(redisPropertiesFilename);
if (input != null) {
try {
config.load(input);
} catch (IOException e) {
throw new RuntimeException(
"An error occurred while reading classpath property '"
+ redisPropertiesFilename
+ "', see nested exceptions", e);
} finally {
try {
input.close();
} catch (IOException e) {
// close quietly
}
}
}
RedisConfig jedisConfig = new RedisConfig();
setConfigProperties(config, jedisConfig);
return jedisConfig;
}
核心的方法就是parseConfiguration方法,该方法从classpath中读取一个redis.properties文件:
host=localhost
port=6379
connectionTimeout=5000
soTimeout=5000
password=
database=0
clientName=
配置文件的key要和RedisConfig中属性名保持一致,否则不能将内容赋值给RedisConfig对象。
并将该配置文件中的内容设置到RedisConfig对象中,并返回;接下来,就是RedisCache使用RedisConfig类创建完成jedisPool;
3 RedisCallback模板接口
在RedisCache中实现了一个简单的模板方法,用来操作Redis:
private Object execute(RedisCallback callback) {
Jedis jedis = pool.getResource();
try {
return callback.doWithRedis(jedis);
} finally {
jedis.close();
}
}
模板接口为RedisCallback,这个接口中就只需要实现了一个doWithRedis方法而已:
public interface RedisCallback {
Object doWithRedis(Jedis jedis);
}
4 RedisCache中的putObject和getObject方法
Cache中最重要的两个方法:putObject和getObject,通过这两个方法来查看mybatis-redis 储存数据的格式:
@Override
public void putObject(final Object key, final Object value) {
execute(new RedisCallback() {
@Override
public Object doWithRedis(Jedis jedis) {
// id:mapper的namespace
jedis.hset(id.toString().getBytes(),
key.toString().getBytes(),
SerializeUtil.serialize(value));
return null;
}
});
}
@Override
public Object getObject(final Object key) {
return execute(new RedisCallback() {
@Override
public Object doWithRedis(Jedis jedis) {
return SerializeUtil.unserialize(jedis.hget(id.toString().getBytes(),
key.toString().getBytes()));
}
});
}
可以很清楚的看到,mybatis-redis在存储数据的时候,是使用的hash结构,把cache的id作为这个hash 的key (cache的id在mybatis中就是mapper的namespace);这个mapper中的查询缓存数据作为 hash 的field,需要缓存的内容直接使用SerializeUtil存储,SerializeUtil和其他的序列化类差不多,负责 对象的序列化和反序列化;
