YYCache源码分析(三)

YYCache源码分析(三)

本文分析YYDiskCache->YYKVStorage实现过程:
YYDiskCacheYYKVStorage一层封装,缓存方式:数据库+文件,下面先分析主要实现类YYKVStorage,再分析表层类YYDiskCache.

img

YYKVStorage.h方法结构图

img

YYKVStorage.h方法解释

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

// 用YYKVStorageItem保存缓存相关参数
@interface YYKVStorageItem : NSObject
// 缓存键值
@property (nonatomic, strong) NSString *key;
// 缓存对象
@property (nonatomic, strong) NSData *value;
// 缓存文件名
@property (nullable, nonatomic, strong) NSString *filename;
// 缓存大小
@property (nonatomic) int size;
// 修改时间
@property (nonatomic) int modTime;
// 最后使用时间
@property (nonatomic) int accessTime;
// 扩展数据
@property (nullable, nonatomic, strong) NSData *extendedData;
@end


// 可以指定缓存类型
typedef NS_ENUM(NSUInteger, YYKVStorageType) {
    // 文件缓存(filename != null)
    YYKVStorageTypeFile = 0,
    // 数据库缓存
    YYKVStorageTypeSQLite = 1,
    // 如果filename != null,则value用文件缓存,缓存的其他参数用数据库缓存;如果filename == null,则用数据库缓存
    YYKVStorageTypeMixed = 2,
};

// 缓存操作实现
@interface YYKVStorage : NSObject

#pragma mark - Attribute
// 缓存路径
@property (nonatomic, readonly) NSString *path;
// 缓存方式
@property (nonatomic, readonly) YYKVStorageType type;
// 是否要打开错误日志
@property (nonatomic) BOOL errorLogsEnabled;

#pragma mark - Initializer
// 这两个方法不能使用,因为实例化对象时要有初始化path、type
- (instancetype)init UNAVAILABLE_ATTRIBUTE;
+ (instancetype)new UNAVAILABLE_ATTRIBUTE;

/**
 *  实例化对象
 *
 *  @param path 缓存路径
 *  @param type 缓存方式
 */
- (nullable instancetype)initWithPath:(NSString *)path type:(YYKVStorageType)type NS_DESIGNATED_INITIALIZER;


#pragma mark - Save Items
/**
 *  添加缓存
 *
 *  @param item 把缓存数据封装到YYKVStorageItem对象
 */
- (BOOL)saveItem:(YYKVStorageItem *)item;

/**
 *  添加缓存
 *
 *  @param key   缓存键值
 *  @param value 缓存对象
 */
- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value;

/**
 *  添加缓存
 *
 *  @param key          缓存键值
 *  @param value        缓存对象
 *  @param filename     缓存文件名称
 *         filename     != null
 *                          则用文件缓存value,并把`key`,`filename`,`extendedData`写入数据库
 *         filename     == null
 *                          缓存方式type:YYKVStorageTypeFile 不进行缓存
 *                          缓存方式type:YYKVStorageTypeSQLite || YYKVStorageTypeMixed 数据库缓存
 *  @param extendedData 缓存拓展数据
 */
- (BOOL)saveItemWithKey:(NSString *)key
                  value:(NSData *)value
               filename:(nullable NSString *)filename
           extendedData:(nullable NSData *)extendedData;


#pragma mark - Remove Items

/**
 *  删除缓存
 */
- (BOOL)removeItemForKey:(NSString *)key;
- (BOOL)removeItemForKeys:(NSArray<NSString *> *)keys;

/**
 *  删除所有内存开销大于size的缓存
 */
- (BOOL)removeItemsLargerThanSize:(int)size;

/**
 *  删除所有时间比time小的缓存
 */
- (BOOL)removeItemsEarlierThanTime:(int)time;

/**
 *  减小缓存占的容量开销,使总缓存的容量开销值不大于maxSize(删除原则:LRU 最久未使用的缓存将先删除)
 */
- (BOOL)removeItemsToFitSize:(int)maxSize;

/**
 *  减小总缓存数量,使总缓存数量不大于maxCount(删除原则:LRU 最久未使用的缓存将先删除)
 */
- (BOOL)removeItemsToFitCount:(int)maxCount;

/**
 *  清空所有缓存
 */
- (BOOL)removeAllItems;
- (void)removeAllItemsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
                               endBlock:(nullable void(^)(BOOL error))end;


#pragma mark - Get Items

/**
 *  读取缓存
 */
- (nullable YYKVStorageItem *)getItemForKey:(NSString *)key;
- (nullable YYKVStorageItem *)getItemInfoForKey:(NSString *)key;
- (nullable NSData *)getItemValueForKey:(NSString *)key;
- (nullable NSArray<YYKVStorageItem *> *)getItemForKeys:(NSArray<NSString *> *)keys;
- (nullable NSArray<YYKVStorageItem *> *)getItemInfoForKeys:(NSArray<NSString *> *)keys;
- (nullable NSDictionary<NSString *, NSData *> *)getItemValueForKeys:(NSArray<NSString *> *)keys;

#pragma mark - Get Storage Status

/**
 *  判断当前key是否有对应的缓存
 */
- (BOOL)itemExistsForKey:(NSString *)key;

/**
 *  获取缓存总数量
 */
- (int)getItemsCount;

/**
 *  获取缓存总内存开销
 */
- (int)getItemsSize;

@end

NS_ASSUME_NONNULL_END

Typically, write data to sqlite is faster than extern file, but
reading performance is dependent on data size. In my test (on iPhone 6 64G),
read data from extern file is faster than from sqlite when the data is larger
than 20KB.

  • If you want to store large number of small datas (such as contacts cache),
    use YYKVStorageTypeSQLite to get better performance.
  • If you want to store large files (such as image cache),
    use YYKVStorageTypeFile to get better performance.
  • You can use YYKVStorageTypeMixed and choice your storage type for each item.

通常情况下,数据写入SQLite比外部文件更快;但读取性能依赖于数据大小。在我的测试中(iPhone 6 64G),当数据大小超过20KB时,从外部文件读取数据的速度比从SQLite数据。

Multiple instances with the same path will make the storage unstable.
具有相同路径的多个实例将使存储不稳定。

Save an item or update the item with 'key' if it already exists.

  • If the type is YYKVStorageTypeFile, then the item.filename should not be empty.
  • If the type is YYKVStorageTypeSQLite, then the item.filename will be ignored.
  • If the type is YYKVStorageTypeMixed, then the item.value will be saved to file
    system if the item.filename is not empty, otherwise it will be saved to sqlite.

根据key保存一个item,如果它已经存在,就更新。key-value pair 键值对;
YYKVStorageTypeFile,item.filename不能为空;YYKVStorageTypeSQLite,item.filename会被忽略;YYKVStorageTypeMixed 如果filename != null,则value用文件缓存,缓存的其他参数用数据库缓存;如果filename == null,则用数据库缓存;

YYKVStorage.m方法结构图

私有方法:
img
公开方法:
img
/*
 File:
 /path/
      /manifest.sqlite
      /manifest.sqlite-shm
      /manifest.sqlite-wal
      /data/
           /e10adc3949ba59abbe56e057f20f883e
           /e10adc3949ba59abbe56e057f20f883e
      /trash/
            /unused_file_or_folder
 
 SQL:
 // 建表语句
 create table if not exists manifest (
    key                 text,
    filename            text,
    size                integer,
    inline_data         blob,
    modification_time   integer,
    last_access_time    integer,
    extended_data       blob,
    primary key(key)
 ); 

 // 创建索引
 create index if not exists last_access_time_idx on manifest(last_access_time);
 */

参考:

在SQLite中使用索引优化查询速度

SQLite3 索引的简单使用
http://hustcat.github.io/
http://www.blogfshare.com/
iOS-SQLite3和FMDB使用

sqlite在多线程下的应用

数据库(SQLITE3函数总结):

SQLLite (三):sqlite3_prepare_v2,sqlite3_step

YYKVStorage.m方法实现

下面分别拎出添加、删除、查找各个主要的方法来讲解

1.添加

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,290评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,399评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,021评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,034评论 0 207
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,412评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,651评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,902评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,605评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,339评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,586评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,076评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,400评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,060评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,851评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,685评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,595评论 2 270

推荐阅读更多精彩内容