持久化
1、持久化整体框架图
一个接口,四个实现类,其中CachePersistAdaptor使用了适配器模式,也就是说CachePersistAdaptor实现了ICachePersist接口,并且其他三个类继承于CachePersistAdaptor类。
2、AOF如何实现的
(持久化到一个文件中)
@Override
public void persist(ICache<K, V> cache) {
log.info("开始 AOF 持久化到文件");
// 1. 创建文件
if(!FileUtil.exists(dbPath)) {
FileUtil.createFile(dbPath);
}
// 2. 持久化追加到文件中
FileUtil.append(dbPath, bufferList);
// 3. 清空 buffer 列表
bufferList.clear();
log.info("完成 AOF 持久化到文件");
}
主要是缓冲区里面是什么,缓冲区是一个ArrayList。做的就是把一个json放进列表中。但是这个json是什么内容?放的是每一次操作缓存的命令,增删改操作
/**
* 添加文件内容到 buffer 列表中
* @param json json 信息
* @since 0.0.10
*/
public void append(final String json) {
if(StringUtil.isNotEmpty(json)) {
bufferList.add(json);
}
}
3、RDB是如何实现的
@Override
public void persist(ICache<K, V> cache) {
Set<Map.Entry<K,V>> entrySet = cache.entrySet();
// 创建文件
FileUtil.createFile(dbPath);
// 清空文件
FileUtil.truncate(dbPath);
for(Map.Entry<K,V> entry : entrySet) {
K key = entry.getKey();
Long expireTime = cache.expire().expireTime(key);
PersistRdbEntry<K,V> persistRdbEntry = new PersistRdbEntry<>();
persistRdbEntry.setKey(key);
persistRdbEntry.setValue(entry.getValue());
persistRdbEntry.setExpire(expireTime);
String line = JSON.toJSONString(persistRdbEntry);
FileUtil.write(dbPath, line, StandardOpenOption.APPEND);
}
}
这用到了一个类型PersistRdbEntry
,是对持久化的东西做一个定义,后面直接将这个PersistRdbEntry对象进行JSON化,然后存到文件中
RDB持久化的方式是,在persist()方法中,使用Map的entrySet()
方法,Set<Map.Entry<K,V>> entrySet = cache.entrySet()
得到一个Set集合,这个Set集合中元素的类型是Map.Entry<K,V>
,对这个集合的元素进行遍历,相当于直接拿出来的是Cache中的元素。正好对应RDB,快照式的持久化方式,直接存储的是数据
然后就是重新过了一遍ICache数据结构,发现自己上一次过的有些乱。重新梳理了一下: