日期:2014-05-16 浏览次数:20513 次
def rdbSave(filename): # 创建临时文件,用于保存rdb数据 tempFile = createTempFile() rio = rioInitWithFile(tempFile) # ---------------------------------- # 1.保存RDB文件版本 rdbSaveVersion(rio, "REDIS" + REDIS_RDB_VERSION) # 2.保存redis所有数据库中的键值对 for db in redisServer.dbs: # 记录键值对所在数据库 rdbSaveSelectDB(rio, db.num) # 保存该数据库中所有键值对 for key, val in db.getKeyValuePairs(): expired_time = getExpiredTime(key) rdbSaveKeyValuePair(rio, key, val, expired_time) # 3.写入RDB文件结束符 rdbSaveEOF(rio, REDIS_RDB_OPCODE_EOF) # 4.写入校验和 rdbSaveCkSum(rio) # ---------------------------------- # 确认数据都被flush到磁盘 fsync() rename(tempFile, filename) def rdbSaveKeyValuePair(rio, key, val, expired_time): if expired_time != -1: # 过滤过期键 if expired_time < now_time: return rdbSaveMillisecondTime(rio, expired_time) # 保存值类型(list? string? hashtable?) rdbSaveValueType(rio, val) # 保存键 rdbSaveKey(rio, key) # 保存值 rdbSaveValue(rio, val)
def rdbLoad(filename): rio = rioInitWithFile(filename); # 设置标记: # a. 服务器状态:rdb_loading = 1 # b. 载入时间:loading_start_time = now_time # c. 载入大小:loading_total_bytes = filename.size startLoading(rio) # ------------------------------------------ # 1.检查该文件是否为RDB文件(即文件开头前5个字符是否为"REDIS") if !checkRDBHeader(rio): redislog("error, Wrong signature trying to load DB from file") return # 2.检查当前RDB文件版本是否兼容(向下兼容) if !checkRDBVersion(rio): redislog("error, Can't handle RDB format version") return # 3.读取文件内容,加载键值对 while not end_of_file: # 每循环一千次就处理一下客户端请求 if loops % 1000 == 0: processClientRequest() key, val, expired_time, dbnum = rdbLoadKeyValuePair() # 过滤过期键 if expired_time != -1 and expired_time <= now_time: continue redisServer.db[dbnum].dict.add(key,value) if expired_time > now_time redisServer.db[dbnum].expires.add(key, expired_time) loops = loops + 1 # 4. 校验和 if (!checkCkSum()): return # ------------------------------------------ # 更新标记:rdb_loading = 0 stopLoading()