Java面试

面试总结(三)-redis

2017-07-23  本文已影响266人  楊小強
redis

写在前面:要想深入了解redis,《redis设计与实现(第二版)》这本书是很不错的选择;关于redis的底层存储结构会在下一篇文章中写,本章切掉这部分内容了。

一、redis 持久化方案(RDB、AOF)

1、RDB(默认持久化方案)
服务运行时将内存文件保存到.rdb 文件中,重启时:读取数据存储文件.rdb,加载到内存中,还原DB。

int rdbSaveBackground(char *filename, rdbSaveInfo *rsi) {
    pid_t childpid;
    long long start;

    if (server.aof_child_pid != -1 || server.rdb_child_pid != -1) return C_ERR;
    if ((childpid = fork()) == 0) {
        int retval;

        /* Child */
        closeListeningSockets(0);
        redisSetProcTitle("redis-rdb-bgsave");
        retval = rdbSave(filename,rsi);
       .............省略一部分
        /* Parent */
        server.stat_fork_time = ustime()-start;
        server.stat_fork_rate = (double) zmalloc_used_memory() * 1000000 / server.stat_fork_time / (1024*1024*1024); /* GB per second. */
        latencyAddSampleIfNeeded("fork",server.stat_fork_time/1000);
        if (childpid == -1) {
            closeChildInfoPipe();
            server.lastbgsave_status = C_ERR;
            serverLog(LL_WARNING,"Can't save in background: fork: %s",
                strerror(errno));
            return C_ERR;
        }
        serverLog(LL_NOTICE,"Background saving started by pid %d",childpid);
        server.rdb_save_time_start = time(NULL);
        server.rdb_child_pid = childpid;
        server.rdb_child_type = RDB_CHILD_TYPE_DISK;
        updateDictResizePolicy();
        return C_OK;
    }
    return C_OK; /* unreached */
}

/* Load an RDB file from the rio stream 'rdb'. On success C_OK is returned,
 * otherwise C_ERR is returned and 'errno' is set accordingly. */
int rdbLoadRio(rio *rdb, rdbSaveInfo *rsi) {
  
    rdb->update_cksum = rdbLoadProgressCallback;
    rdb->max_processing_chunk = server.loading_process_events_interval_bytes;
   
    while(1) {
        。。。 省略一部分代码
        /* Read type. */
        if ((type = rdbLoadType(rdb)) == -1) goto eoferr;

        /* Handle special types. */
        if (type == RDB_OPCODE_EXPIRETIME) {
            /* EXPIRETIME: load an expire associated with the next key
             * to load. Note that after loading an expire we need to
             * load the actual type, and continue. */
            if ((expiretime = rdbLoadTime(rdb)) == -1) goto eoferr;
            /* We read the time so we need to read the object type again. */
            if ((type = rdbLoadType(rdb)) == -1) goto eoferr;
            /* the EXPIRETIME opcode specifies time in seconds, so convert
             * into milliseconds. */
            expiretime *= 1000;
        } else if (type == RDB_OPCODE_EXPIRETIME_MS) {
            /* EXPIRETIME_MS: milliseconds precision expire times introduced
             * with RDB v3. Like EXPIRETIME but no with more precision. */
            if ((expiretime = rdbLoadMillisecondTime(rdb)) == -1) goto eoferr;
            /* We read the time so we need to read the object type again. */
            if ((type = rdbLoadType(rdb)) == -1) goto eoferr;
        } else if (type == RDB_OPCODE_EOF) {
            /* EOF: End of file, exit the main loop. */
            break;
        }
            decrRefCount(auxkey);
            decrRefCount(auxval);
            continue; /* Read type again. */
        }
。。。 省略一部分代码
}

rdb 文件保存时间点,在redis.conf中进行配置 ' save <seconds> <changes>'

################################ SNAPSHOTTING  ################################
#
# Save the DB on disk:
#
#   save <seconds> <changes>
#
#   Will save the DB if both the given number of seconds and the given
#   number of write operations against the DB occurred.
#
#   In the example below the behaviour will be to save:
#   after 900 sec (15 min) if at least 1 key changed
#   after 300 sec (5 min) if at least 10 keys changed
#   after 60 sec if at least 10000 keys changed
#
#   Note: you can disable saving completely by commenting out all "save" lines.
#
#   It is also possible to remove all the previously configured save
#   points by adding a save directive with a single empty string argument
#   like in the following example:
#
#   save ""

save 900 1    //900秒保存一个key
save 300 10    //300秒保存10个key
save 60 10000    //60秒保存10000个key

2、AOF
aof是一个协议文本方式的存储方案,对数据库的操作命令记录到aof文件中,达到记录记录数据的目的(有点类似MySQL的bin log)
写入流程:

上面的常量,也是在redis.conf 中配置aof的参数。 默认appendfsync no

aof的出现是为了解决什么问题?官方说明:rds 这种方案本来已经是一种很好的方案了,能够适应绝大多数的情况,但是在redis进程或电源发生故障的情况下,可能会造成小部份的数据丢失,这取决于配置的保存时间点;
Appendonly是一种能够提供非常好的持久化的模式,例如使用默认的Fsync方案,redis能在发生服务器电源故障或操作系统仍然正常运行但redis进程莫名挂掉的情况下,只丢失1秒的数据。 aof与rdb模式可以同时启用,这并不冲突。如果aof是可用的,那redis启动时将自动加载aof,这个文件能够提供更好的持久性保障。

原文:
############################## APPEND ONLY MODE ###############################

# By default Redis asynchronously dumps the dataset on disk. This mode is
# good enough in many applications, but an issue with the Redis process or
# a power outage may result into a few minutes of writes lost (depending on
# the configured save points).
#
# The Append Only File is an alternative persistence mode that provides
# much better durability. For instance using the default data fsync policy
# (see later in the config file) Redis can lose just one second of writes in a
# dramatic event like a server power outage, or a single write if something
# wrong with the Redis process itself happens, but the operating system is
# still running correctly.
#
# AOF and RDB persistence can be enabled at the same time without problems.
# If the AOF is enabled on startup Redis will load the AOF, that is the file
# with the better durability guarantees.
#
# Please check http://redis.io/topics/persistence for more information.
AOF VS RDB

二、redis 常用数据结构

三、redis的启动流程分析

任何一个组件,包括redis,MySQL或者说servlet的启动过程都是有着很多的相似之处,对比学习是一个很好的学习方法;

redis 启动过程包括两个主要操作:初始化服务器配置、初始化功能模块
初始化服务器配置,主要做以下事情

下面是转的一个流程图,整个过程表达的很清晰


图片转自http://processon.com/chart_image/id/58441b02e4b0e742e493404c.png 如有侵权请联系本人
上一篇 下一篇

猜你喜欢

热点阅读