上一篇 <<
1.底层实现原理
先请求二级缓存中的数据,不存在的话读取一级缓存,如果没有的话则从数据库中读取,之后分别缓存一级缓存和二级缓存。
二级缓存必须在session关闭或提交的时候,才会将数据真正写入缓存中,要不然都在一个临时的对象中。
Springboot自带拦截器,每次请求都会执行commit的操作,也就自动将数据存储到二级缓存中,不用手动去调用。
2.核心源码
执行到二级缓存org.apache.ibatis.executor.CachingExecutor#query(org.apache.ibatis.mapping.MappedStatement, java.lang.Object, org.apache.ibatis.session.RowBounds, org.apache.ibatis.session.ResultHandler, org.apache.ibatis.cache.CacheKey, org.apache.ibatis.mapping.BoundSql)
@Override
public List query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql)
throws SQLException {
//判断是否配置了我们二级缓存 如果配置了cache != null
Cache cache = ms.getCache();
if (cache != null) {
flushCacheIfRequired(ms);
if (ms.isUseCache() && resultHandler == null) {
ensureNoOutParams(ms, parameterObject, boundSql);
@SuppressWarnings("unchecked")
// 先查询二级缓存---(redis)
List list = (List) tcm.getObject(cache, key);
// 如果二级缓存中没有该数据 则查询 简单执行器
if (list == null) {
// 简单执行器---base执行器 调用一级缓存查询-----装饰模式
list = delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
// 如果一级缓存中能够查询到数据 则将一级缓存数据 存放到二级缓存中
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
}
}
return delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
}
二级缓存底层也是采用 HashMap集合实现
public class TransactionalCacheManager {
private Map transactionalCaches = new HashMap();
public void clear(Cache cache) {
getTransactionalCache(cache).clear();
}
public Object getObject(Cache cache, CacheKey key) {
return getTransactionalCache(cache).getObject(key);
}
public void putObject(Cache cache, CacheKey key, Object value) {
getTransactionalCache(cache).putObject(key, value);
}
public void commit() {
for (TransactionalCache txCache : transactionalCaches.values()) {
txCache.commit();
}
}
public void rollback() {
for (TransactionalCache txCache : transactionalCaches.values()) {
txCache.rollback();
}
}
private TransactionalCache getTransactionalCache(Cache cache) {
TransactionalCache txCache = transactionalCaches.get(cache);
if (txCache == null) {
txCache = new TransactionalCache(cache);
transactionalCaches.put(cache, txCache);
}
return txCache;
}
}
List list = (List) tcm.getObject(cache, key);
if (list == null) {
list = delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql);
// 回调到我们自定义的 将数据存入到redis中
tcm.putObject(cache, key, list); // issue #578 and #116
}
return list;
3.二级缓存在什么时候存放数据到redis中呢?
1.先将一级缓存中数据 先放入到 二级缓存临时 map集合中
读取一级缓存或数据库后
CachingExecutor.his.tcm.putObject(cache, key, list);
TransactionalCacheManager.getTransactionalCache(cache).putObject(key, value);
TransactionalCacheManager.entriesToAddOnCommit.put(key, object);//先临时存放
2.当我们调用commit/close时将二级缓存临时 map集合中数据遍历 写入到redis中
sqlSession.close();/ sqlSession.commit();
CachingExecutor.tcm.commit();
Iterator i$ = CachingExecutor.transactionalCaches.values().iterator();
while(i$.hasNext()) {
TransactionalCache txCache = (TransactionalCache)i$.next();
txCache.commit();
{
TransactionalCache.flushPendingEntries();
TransactionalCache.reset();
}
}
//TransactionalCache.flushPendingEntries()的实现
将临时存放的数据写入到二级缓存中
private void flushPendingEntries() {
Iterator i$ = this.entriesToAddOnCommit.entrySet().iterator();
while(i$.hasNext()) {
Entry
//TransactionalCache.reset();
重置临时存放的数据
private void reset() {
this.clearOnCommit = false;
this.entriesToAddOnCommit.clear();
this.entriesMissedInCache.clear();
}
4.二级缓存如何开启
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class MybatisRedisCache implements Cache {
private static Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);
private Jedis redisClient = createReids();
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private String id;
public MybatisRedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id=" + id);
this.id = id;
}
public String getId() {
return this.id;
}
public int getSize() {
return Integer.valueOf(redisClient.dbSize().toString());
}
public void putObject(Object key, Object value) {
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:" + key + "=" + value);
redisClient.set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));
}
public Object getObject(Object key) {
Object value = SerializeUtil.unserialize(redisClient.get(SerializeUtil.serialize(key.toString())));
logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:" + key + "=" + value);
return value;
}
public Object removeObject(Object key) {
return redisClient.expire(SerializeUtil.serialize(key.toString()), 0);
}
public void clear() {
redisClient.flushDB();
}
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
protected static Jedis createReids() {
JedisPool pool = new JedisPool("127.0.0.1", 6379);
return pool.getResource();
}
}
推荐阅读:
<<