MyBatis缓存
Mybatis总共支持两级缓存
- 一级缓存是SqlSession级别的缓存,在操作数据库时需要构造sqlSession对象,在该对象中有一个数据结构(HashMap)用来存储缓存数据,不同的sqlSession之间的缓存数据区域(HashMap)是互相不影响的。
- 二级缓存是mapper级别的缓存,和namspace相关联,多个sqlSession去操作同一个Mapper的sql语句,多个sqlSession可以公用二级缓存,二级缓存是夸sqlSession的。
一级缓存
一个例子如下:
该例子中对user进行了两次查询,但是sql只执行了一次
public void test1(){
//根据 sqlSessionFactory 产生 session
SqlSession sqlSession = sessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//第一次查询,发出sql语句,并将查询出来的结果放进缓存中
User u1 = userMapper.selectUserByUserId(1);
System.out.println(u1);
//第二次查询,由于是同一个sqlSession,会在缓存中查询结果
//如果有,则直接从缓存中取出来,不和数据库进行交互
User u2 = userMapper.selectUserByUserId(1);
System.out.println(u2);
sqlSession.close();
}
在上面代码的两次查询中加入下面代码,会发现查询sql执行两次
//第二步进行了一次更新操作,sqlSession.commit()
u1.setSex("女");
userMapper.updateUserByUserId(u1);
sqlSession.commit();
//第二次查询,由于是同一个sqlSession.commit(),会清空缓存信息
总结
- 如果多次执行相同的sql查询,mybatis在第一次查询后会将信息存到一级缓存中。
- 如果中间sqlSession执行commit操作(插入,更新,删除)则会清空sqlSession中的一级缓存,这样做的目的为了让缓存中存储的是最新的信息,避免脏读。
一级缓存原理
研究sqlSession的源码我们会发现在sqlSession中有clearCache这个方法。他的继承关系如下:
再深入分析,在PerpetualCache中的clear()方法中,会调用的cache.clear()方法。而这个cache的实现就是 priave Map cache = new HashMap();所以cache.clear()其实就是map.clear(),也就是说缓存其实就是本地存放的一个map对象,每一个SqlSession都会存放一个map对象的引用。而该map的创建则在Executor中,Executor是用来执行SQL请求的执行器,其中有一个createCacheKey()方法,该方法由BaseExecutor执行。代码如下:
CacheKey cacheKey = new CacheKey();
//MappedStatement 的 id
// id就是Sql语句的所在位置包名+类名+ SQL名称
cacheKey.update(ms.getId());
// offset 就是 0
cacheKey.update(rowBounds.getOffset());
// limit 就是 Integer.MAXVALUE
cacheKey.update(rowBounds.getLimit());
//具体的SQL语句
cacheKey.update(boundSql.getSql());
//后面是update了sql中带的参数
cacheKey.update(value);
...
if (configuration.getEnvironment() != null) {
// issue #176
cacheKey.update(configuration.getEnvironment().getId());
}
创建缓存key会经过一系列的update方法,update方法由CacheKey这个对象来执行,这个update方法最终会由updateList的list来把上文代码中的5个值存进去。其中configuration.getEnvironment().getId()是定义在mybatis-config.xml中的标签的id。
一级缓存同时也叫作查询缓存,多运用在SQL查询操作中,对localCache的put操作在queryFromDatabase方法中,代码如下:
// queryFromDatabase 方法
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter,
RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql
boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
}finally {
localCache.removeObject(key);
}
//这里对查询的结果进行了缓存
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
private Map<Object, Object> cache = new HashMap<Object, Object>();
@Override
public void putObject(Object key, Object value) {
cache.put(key, value);
}
可以看出localCache对象的put方法最终会交给Map来进行存放。
二级缓存
二级缓存的原理和一级缓存的原理一样,第一次查询的时候,会将数据放入缓存中,然后第二次查询则会直接在缓存中取。但是一级缓存是基于sqlSession的,而二级缓存是基于mqpper文件的namesqpce的,也就是多个sqlSession可以共享一个mapper中的二级缓存区域,并且如果两个mapper的namesqpce相同,即使是两个mapper,这两个mapper中执行的sql查询也会存在相同的二级缓存区域中。
开启二级缓存
二级缓存需要手动开启,需要在全局配置文件sqlMapConfig.xml中加入如下代码
<setting/>
<setting name="cacheEnabled" value="true"/>
<settings/>
然后在Mapper.xml文件中开启缓存
<cache><cache/>
可以看到mapper.xml文件中就这么一个空标签,其实这里可以配置type = PerpetualCache,这个类是mybatis默认实现的缓存功能类,不写则使用默认,也可以通过实现Cache接口来自定义缓存。
public class PerpetualCache implements Cache {
private final String id;
private MapcObject, Object> cache = new HashMapC);
public PerpetualCache(St ring id) {
this.id = id;
}
可以看到二级缓存的底层仍然是HashMap结构。
开启二级缓存只用,我们要将需要缓存的pojo实现Serializable接口,为了将缓存数据取出执行反序列化操作,因为二级缓存数据存储不一定只在内存中,有可能存在磁盘中,如果我们再取这个缓存的话,就需要反序列化。所以mybatis中的pojo都去实现Serializable接口。
useCache和flushCache
mybatis中还可以配置useCache和flushCache等配置项,useCache用来设置是否禁用二级缓存,在statement中设置useCache=false可以禁用当前的select语句的二级缓存。
<select id="selectUserByUserId" useCache="false"
resultType="com.lagou.pojo.User" parameterType="int">
select * from user where id=#{id}
</select>
设置statement配置中的flushCache=true则表示执行语句后刷新缓存,如果不刷新缓存则可能造成脏读的情况。
二级缓存整合redis
上文我们说道mybatis可以使用默认的二级缓存PerpetualCache,可以配置成其他自定义的缓存。redis则是一个我们服务中常用的缓存数据库,相比mybatis自带的缓存,redis可以提供分布式缓存服务,能够适应更加复杂的环境。
mybatis提供了一个针对cache接口的redis实现类,该类存在mybatis-redis包中,我们要实现其接口首先要引入这个包。
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-redis</artifactId>
<version>1.0.0-beta2</version>
</dependency>
在mapper.xml配置文件中将修改
<cache type="org.mybatis.caches.redis.RedisCache" />
同时配置redis.properrise
redis.host=localhost
redis.port=6379
redis.connectionTimeout=5000
redis.password=
redis.database=0
修改完上述配置后即可使用redis替换掉mybatis原默认二级缓存。
源码分析
RedisCache和大家普遍实现的Mybatis缓存方案大同小异,无非是实现Cache接口,并使用jedis操作缓存,不过该项目在设计细节上有些许区别。
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。RedisConfig继承了JedisConfig,并提供了host,port等属性的包装。
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文件,并将配置文件中的内容设置到RedisConfig对象中,并返回;然后RedisCache使用RedisConfig类创建完成的RedisPool。
private Object execute(RedisCallback callback) {
Jedis jedis = pool.getResource();
try {
return callback.doWithRedis(jedis);
} finally {
jedis.close();
}
}
RedisCache中实现了一个模板方法,用来操作redis,模板接口为RedisCallback。
Cache中最重要的两个方法:putObject和getObject的实现如下:
@Override
public void putObject(final Object key, final Object value) {
execute(new RedisCallback() {
@Override
public Object doWithRedis(Jedis jedis) {
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()));
}
});
}
可以看到,mybati-redis在存储数据的时候,是使用hash结构,把cache的id作为hash的key(id在mybatis中就是mapper的namespace);缓存的数据则作为hash的value,通过Serializeutil进行数据的序列化和反序列化。