YYCache源码分析(三)

来源:互联网 发布:怎么修复excel软件 编辑:程序博客网 时间:2024/05/17 12:46

YYKVStorage

YYDiskCache中文件存放的路径和数据库表的结构,如下图:

这里写图片描述

在每个path下面,都有data和trash文件夹,其中data文件是存放数据的文件缓存,文件名都是通过md5加密的,trash则是在放置丢弃的缓存文件的文件夹。此外path下的manifest.sqlite则是数据库的文件,manifest.sqlite-shm和manifest.sqlite-wal是sqlite数据库WAL机制所需文件。

WAL机制的原理是:我们在写数据时,并不是直接操作数据库文件,而是操作一个WAL文件,这样当我们插入、或者删除数据时,只是写一条操作语句到WAL文件,当WAL文件达到一定数量级(默认是1000page)时,sqlite就会把数据同步到数据库文件中。其带来的不足之处是读数据时,可能要同时考虑到WAL文件与数据库文件,所以读数据性能会有一定下降。但这个对于移动端的数据量来说表现得并不明显。所以数据库在删除数据后,数据库文件大小有时候反而会增大。但并不会无限制地增大,当增长到一定数量时,其就会变小。

SQLite3:

SQLite3的使用过程大致如下:

  • sqlite3_open():打开数据库这个函数打开一个sqlite数据库文件的连接并且返回一个数据库连接对象。
  • sqlite3_prepare():这个函数将sql文本转换成一个准备语句(prepared statement)对象,同时返回这个对象的指针。这个接口需要一个数据库连接指针以及一个要准备的包含SQL语句的文本。它实际上并不执行(evaluate)这个SQL语句,它仅仅为执行准备这个sql语句。sqlite3_prepare执行代价昂贵,所以通常尽可能的重用prepared语句
  • sqlite3_setp():这个过程用于执行有前面sqlite3_prepare创建的准备语句。这个语句执行到结果的第一行可用的位置。继续前进到结果的第二行的话,只需再次调用sqlite3_setp()。继续调用sqlite3_setp()知道这个语句完成,那些不返回结果的语句(如:INSERT,UPDATE,或DELETE),sqlite3_step()只执行一次就返回
  • sqlite3_column():每次sqlite3_step得到一个结果集的列停下后,这个过程就可以被多次调用去查询这个行的各列的值。对列操作是有多个函数,均以sqlite3_column为前缀
  • sqlite3_finalize:这个过程销毁前面被sqlite3_prepare创建的准备语句,每个准备语句都必须使用这个函数去销毁以防止内存泄露。
  • sqlite3_close:这个过程关闭前面使用sqlite3_open打开的数据库连接,任何与这个连接相关的准备语句必须在调用这个关闭函数之前被释放

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;@endNS_ASSUME_NONNULL_END</nsstring *></nsstring *, nsdata *></nsstring *></yykvstorageitem *></nsstring *></yykvstorageitem *></nsstring *></foundation>

1.添加

// 添加缓存- (BOOL)saveItemWithKey:(NSString *)key value:(NSData *)value filename:(NSString *)filename extendedData:(NSData *)extendedData {    if (key.length == 0 || value.length == 0) return NO;    if (_type == YYKVStorageTypeFile && filename.length == 0) {        //** `缓存方式为YYKVStorageTypeFile(文件缓存)`并且`未传缓存文件名`则不缓存(忽略) **        return NO;    }    if (filename.length) {        //** 存在文件名则用文件缓存,并把`key`,`filename`,`extendedData`写入数据库 **        // 缓存数据写入文件        if (![self _fileWriteWithName:filename data:value]) {            return NO;        }        // 把`key`,`filename`,`extendedData`写入数据库,存在filenam,则不把value缓存进数据库        if (![self _dbSaveWithKey:key value:value fileName:filename extendedData:extendedData]) {            // 如果数据库操作失败,删除之前的文件缓存            [self _fileDeleteWithName:filename];            return NO;        }        return YES;    } else {        if (_type != YYKVStorageTypeSQLite) {            // ** 缓存方式:非数据库 **            // 根据缓存key查找缓存文件名            NSString *filename = [self _dbGetFilenameWithKey:key];            if (filename) {                // 删除文件缓存                [self _fileDeleteWithName:filename];            }        }        // 把缓存写入数据库        return [self _dbSaveWithKey:key value:value fileName:nil extendedData:extendedData];    }}// 把data写入文件- (BOOL)_fileWriteWithName:(NSString *)filename data:(NSData *)data {    // 拼接文件路径    NSString *path = [_dataPath stringByAppendingPathComponent:filename];    // 写入文件    return [data writeToFile:path atomically:NO];}// 写入数据库- (BOOL)_dbSaveWithKey:(NSString *)key value:(NSData *)value fileName:(NSString *)fileName extendedData:(NSData *)extendedData {    // 执行sql语句    NSString *sql = @"insert or replace into manifest (key, filename, size, inline_data, modification_time, last_access_time, extended_data) values (?1, ?2, ?3, ?4, ?5, ?6, ?7);";    // 所有sql执行前,都必须能run    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];    if (!stmt) return NO;    // 时间    int timestamp = (int)time(NULL);    // 绑定参数值    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);    sqlite3_bind_text(stmt, 2, fileName.UTF8String, -1, NULL);    sqlite3_bind_int(stmt, 3, (int)value.length);    if (fileName.length == 0) {        // fileName为null时,缓存value        sqlite3_bind_blob(stmt, 4, value.bytes, (int)value.length, 0);    } else {        // fileName不为null时,不缓存value        sqlite3_bind_blob(stmt, 4, NULL, 0, 0);    }    sqlite3_bind_int(stmt, 5, timestamp);    sqlite3_bind_int(stmt, 6, timestamp);    sqlite3_bind_blob(stmt, 7, extendedData.bytes, (int)extendedData.length, 0);    // 执行操作    int result = sqlite3_step(stmt);    if (result != SQLITE_DONE) {        //** 未完成执行数据库 **        // 输出错误logs        if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite insert error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));        return NO;    }    return YES;}// 将sql编译成stmt- (sqlite3_stmt *)_dbPrepareStmt:(NSString *)sql {    if (![self _dbCheck] || sql.length == 0 || !_dbStmtCache) return NULL;    // 从_dbStmtCache字典里取之前编译过sql的stmt(优化)    sqlite3_stmt *stmt = (sqlite3_stmt *)CFDictionaryGetValue(_dbStmtCache, (__bridge const void *)(sql));    if (!stmt) {        // 将sql编译成stmt        int result = sqlite3_prepare_v2(_db, sql.UTF8String, -1, &stmt, NULL);        if (result != SQLITE_OK) {            //** 未完成执行数据库 **            // 输出错误logs            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite stmt prepare error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));            return NULL;        }        // 将新的stmt缓存到字典        CFDictionarySetValue(_dbStmtCache, (__bridge const void *)(sql), stmt);    } else {        // 重置stmt状态        sqlite3_reset(stmt);    }    return stmt;}// 删除文件- (BOOL)_fileDeleteWithName:(NSString *)filename {    NSString *path = [_dataPath stringByAppendingPathComponent:filename];    return [[NSFileManager defaultManager] removeItemAtPath:path error:NULL];}// 从数据库查找文件名- (NSString *)_dbGetFilenameWithKey:(NSString *)key {    // 准备执行sql    NSString *sql = @"select filename from manifest where key = ?1;";    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];    if (!stmt) return nil;    // 绑定参数    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);    // 执行操作    int result = sqlite3_step(stmt);    if (result == SQLITE_ROW) {        //** 存在可读的row **        // 取出stmt中的数据        char *filename = (char *)sqlite3_column_text(stmt, 0);        if (filename && *filename != 0) {            // 转utf8 string            return [NSString stringWithUTF8String:filename];        }    } else {        if (result != SQLITE_DONE) {            //** 未完成执行数据库 **            // 输出错误logs            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));        }    }    return nil;}

2.删除

// 删除缓存- (BOOL)removeItemForKey:(NSString *)key {    if (key.length == 0) return NO;    // 判断缓存方式    switch (_type) {        case YYKVStorageTypeSQLite: {            //** 数据库缓存 **            // 删除数据库记录            return [self _dbDeleteItemWithKey:key];        } break;        case YYKVStorageTypeFile:        case YYKVStorageTypeMixed: {            //** 数据库缓存 或 文件缓存 **            // 查找缓存文件名            NSString *filename = [self _dbGetFilenameWithKey:key];            if (filename) {                // 删除文件缓存                [self _fileDeleteWithName:filename];            }            // 删除数据库记录            return [self _dbDeleteItemWithKey:key];        } break;        default: return NO;    }}// 删除数据库记录- (BOOL)_dbDeleteItemWithKey:(NSString *)key {    // 准备执行sql    NSString *sql = @"delete from manifest where key = ?1;";    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];    if (!stmt) return NO;    // 绑定参数    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);    // 执行操作    int result = sqlite3_step(stmt);    if (result != SQLITE_DONE) {        //** 未完成执行数据库 **        // 输出错误logs        if (_errorLogsEnabled) NSLog(@"%s line:%d db delete error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));        return NO;    }    return YES;}

3.查找

// 查找缓存- (YYKVStorageItem *)getItemForKey:(NSString *)key {    if (key.length == 0) return nil;    // 数据库查询    YYKVStorageItem *item = [self _dbGetItemWithKey:key excludeInlineData:NO];    if (item) {        //** 数据库存在记录 **        // 更新操作时间        [self _dbUpdateAccessTimeWithKey:key];        if (item.filename) {            //** 存在文件名 **            // 读入文件            item.value = [self _fileReadWithName:item.filename];            if (!item.value) {                //** 未找到文件 **                // 删除数据库记录                [self _dbDeleteItemWithKey:key];                item = nil;            }        }    }    return item;}// 数据库查询- (YYKVStorageItem *)_dbGetItemWithKey:(NSString *)key excludeInlineData:(BOOL)excludeInlineData {    // 准备执行sql    NSString *sql = excludeInlineData ? @"select key, filename, size, modification_time, last_access_time, extended_data from manifest where key = ?1;" : @"select key, filename, size, inline_data, modification_time, last_access_time, extended_data from manifest where key = ?1;";    sqlite3_stmt *stmt = [self _dbPrepareStmt:sql];    if (!stmt) return nil;    // 绑定参数    sqlite3_bind_text(stmt, 1, key.UTF8String, -1, NULL);    YYKVStorageItem *item = nil;    // 执行操作    int result = sqlite3_step(stmt);    if (result == SQLITE_ROW) {        //** 存在可读的row **        // 获取YYKVStorageItem        item = [self _dbGetItemFromStmt:stmt excludeInlineData:excludeInlineData];    } else {        if (result != SQLITE_DONE) {            //** 未完成执行数据库 **            // 输出错误logs            if (_errorLogsEnabled) NSLog(@"%s line:%d sqlite query error (%d): %s", __FUNCTION__, __LINE__, result, sqlite3_errmsg(_db));        }    }    return item;}// 转换模型YYKVStorageItem- (YYKVStorageItem *)_dbGetItemFromStmt:(sqlite3_stmt *)stmt excludeInlineData:(BOOL)excludeInlineData {    int i = 0;    // 取出数据    char *key = (char *)sqlite3_column_text(stmt, i++);    char *filename = (char *)sqlite3_column_text(stmt, i++);    int size = sqlite3_column_int(stmt, i++);    const void *inline_data = excludeInlineData ? NULL : sqlite3_column_blob(stmt, i);    int inline_data_bytes = excludeInlineData ? 0 : sqlite3_column_bytes(stmt, i++);    int modification_time = sqlite3_column_int(stmt, i++);    int last_access_time = sqlite3_column_int(stmt, i++);    const void *extended_data = sqlite3_column_blob(stmt, i);    int extended_data_bytes = sqlite3_column_bytes(stmt, i++);    // 赋值模型    YYKVStorageItem *item = [YYKVStorageItem new];    if (key) item.key = [NSString stringWithUTF8String:key];    if (filename && *filename != 0) item.filename = [NSString stringWithUTF8String:filename];    item.size = size;    if (inline_data_bytes > 0 && inline_data) item.value = [NSData dataWithBytes:inline_data length:inline_data_bytes];    item.modTime = modification_time;    item.accessTime = last_access_time;    if (extended_data_bytes > 0 && extended_data) item.extendedData = [NSData dataWithBytes:extended_data length:extended_data_bytes];    return item;}
原创粉丝点击