redis服务器负责与多个客户端建立网络连接,处理客户端发送的命令请求,在数据库中保存客户端执行命令所才参数的数据,并通过资源管理来维持服务器自身的运转。 1. 命令请求的执行过程 以set命令为例: redis set key valueredis ok 1.1 发送命令请求 1.2读
redis服务器负责与多个客户端建立网络连接,处理客户端发送的命令请求,在数据库中保存客户端执行命令所才参数的数据,并通过资源管理来维持服务器自身的运转。
1. 命令请求的执行过程以set命令为例:
redis> set key valueredis> ok
1.1 发送命令请求
1.2读取命令请求当客户端与服务器之间的连接套接字因为客户端的写入而变的可读时,服务器将调用命令请求处理器来执行如下操作:
①读取套接字中协议格式的命令请求,保存到客户端状态的输入缓冲区。
②对缓冲区中的命令请求进行分析,提取命令参数及个数,保存到客户端状态的argv属性和argc属性。
③调用命令执行器执行客户端指定的命令。
1.3 命令执行器(1)查找命令实现
根据客户端状态的 argv[0] 参数, 在命令表(command table)中查找参数所指定的命令, 并将找到的命令保存到客户端状态的 cmd 属性里面。
命令表是一个字典, 字典的键是一个个命令名字,比如 “set” 、 “get” 、 “del” ,等等; 而字典的值则是一个个 rediscommand 结构, 每个 rediscommand 结构记录了一个 redis 命令的实现信息。
(2)执行预备操作
(3)调用命令的实现函数
client->cmd->proc(client);
(4)执行后续工作
1.4 将命令回复发送给客户端命令实现函数会将命令回复保存到客户端的输出缓冲区里面, 并为客户端的套接字关联命令回复处理器, 当客户端套接字变为可写状态时, 服务器就会执行命令回复处理器, 将保存在客户端输出缓冲区中的命令回复发送给客户端。
当命令回复发送完毕之后, 回复处理器会清空客户端状态的输出缓冲区, 为处理下一个命令请求做好准备。
1.5 客户端接收并打印命令回复
2. servercron函数redis服务器中的servercron函数默认每隔100毫秒执行一次,这个函数负责管理服务器的资源,并保持服务器自身的良好运转。
主要工作包括:更新服务器状态信息,处理服务器接收的sigterm信号,管理客户端资源和数据库状态,检查并执行持久化操作等。
主要工作包括:
更新服务器的各类统计信息,比如时间,内存占用,数据库占用情况等。
清理数据库中过期键值对。
关闭和清理连接失效的客户端
尝试进行aof或rdb持久化操作。
如果服务器是主服务器,对从服务器进行定期同步。
如果处理集群模式,对集群进行定期同步和连接测试。
redisserver结构/servercron函数属性
/* this is our timer interrupt, called server.hz times per second. * * 这是 redis 的时间中断器,每秒调用 server.hz 次。 * * here is where we do a number of things that need to be done asynchronously. * for instance: * * 以下是需要异步执行的操作: * * - active expired keys collection (it is also performed in a lazy way on * lookup). * 主动清除过期键。 * * - software watchdog. * 更新软件 watchdog 的信息。 * * - update some statistic. * 更新统计信息。 * * - incremental rehashing of the dbs hash tables. * 对数据库进行渐增式 rehash * * - triggering bgsave / aof rewrite, and handling of terminated children. * 触发 bgsave 或者 aof 重写,并处理之后由 bgsave 和 aof 重写引发的子进程停止。 * * - clients timeout of different kinds. * 处理客户端超时。 * * - replication reconnection. * 复制重连 * * - many more... * 等等。。。 * * everything directly called here will be called server.hz times per second, * so in order to throttle execution of things we want to do less frequently * a macro is used: run_with_period(milliseconds) { .... } * * 因为 servercron 函数中的所有代码都会每秒调用 server.hz 次, * 为了对部分代码的调用次数进行限制, * 使用了一个宏 run_with_period(milliseconds) { ... } , * 这个宏可以将被包含代码的执行次数降低为每 milliseconds 执行一次。 */int servercron(struct aeeventloop *eventloop, long long id, void *clientdata) { int j; redis_notused(eventloop); redis_notused(id); redis_notused(clientdata); /* software watchdog: deliver the sigalrm that will reach the signal * handler if we don't return here fast enough. */ if (server.watchdog_period) watchdogschedulesignal(server.watchdog_period); /* update the time cache. */ updatecachedtime(); // 记录服务器执行命令的次数 run_with_period(100) trackoperationspersecond(); /* we have just redis_lru_bits bits per object for lru information. * so we use an (eventually wrapping) lru clock. * * note that even if the counter wraps it's not a big problem, * everything will still work but some object will appear younger * to redis. however for this to happen a given object should never be * touched for all the time needed to the counter to wrap, which is * not likely. * * 即使服务器的时间最终比 1.5 年长也无所谓, * 对象系统仍会正常运作,不过一些对象可能会比服务器本身的时钟更年轻。 * 不过这要这个对象在 1.5 年内都没有被访问过,才会出现这种现象。 * * note that you can change the resolution altering the * redis_lru_clock_resolution define. * * lru 时间的精度可以通过修改 redis_lru_clock_resolution 常量来改变。 */ server.lruclock = getlruclock(); /* record the max memory used since the server was started. */ // 记录服务器的内存峰值 if (zmalloc_used_memory() > server.stat_peak_memory) server.stat_peak_memory = zmalloc_used_memory(); /* sample the rss here since this is a relatively slow call. */ server.resident_set_size = zmalloc_get_rss(); /* we received a sigterm, shutting down here in a safe way, as it is * not ok doing so inside the signal handler. */ // 服务器进程收到 sigterm 信号,关闭服务器 if (server.shutdown_asap) { // 尝试关闭服务器 if (prepareforshutdown(0) == redis_ok) exit(0); // 如果关闭失败,那么打印 log ,并移除关闭标识 redislog(redis_warning,sigterm received but errors trying to shut down the server, check the logs for more information); server.shutdown_asap = 0; } /* show some info about non-empty databases */ // 打印数据库的键值对信息 run_with_period(5000) { for (j = 0; j changes && server.unixtime-server.lastsave > sp->seconds && (server.unixtime-server.lastbgsave_try > redis_bgsave_retry_delay || server.lastbgsave_status == redis_ok)) { redislog(redis_notice,%d changes in %d seconds. saving..., sp->changes, (int)sp->seconds); // 执行 bgsave rdbsavebackground(server.rdb_filename); break; } } /* trigger an aof rewrite if needed */ // 出发 bgrewriteaof if (server.rdb_child_pid == -1 && server.aof_child_pid == -1 && server.aof_rewrite_perc && // aof 文件的当前大小大于执行 bgrewriteaof 所需的最小大小 server.aof_current_size > server.aof_rewrite_min_size) { // 上一次完成 aof 写入之后,aof 文件的大小 long long base = server.aof_rewrite_base_size ? server.aof_rewrite_base_size : 1; // aof 文件当前的体积相对于 base 的体积的百分比 long long growth = (server.aof_current_size*100/base) - 100; // 如果增长体积的百分比超过了 growth ,那么执行 bgrewriteaof if (growth >= server.aof_rewrite_perc) { redislog(redis_notice,starting automatic rewriting of aof on %lld%% growth,growth); // 执行 bgrewriteaof rewriteappendonlyfilebackground(); } } } // 根据 aof 政策, // 考虑是否需要将 aof 缓冲区中的内容写入到 aof 文件中 /* aof postponed flush: try at every cron cycle if the slow fsync * completed. */ if (server.aof_flush_postponed_start) flushappendonlyfile(0); /* aof write errors: in this case we have a buffer to flush as well and * clear the aof error in case of success to make the db writable again, * however to try every second is enough in case of 'hz' is set to * an higher frequency. */ run_with_period(1000) { if (server.aof_last_write_status == redis_err) flushappendonlyfile(0); } /* close clients that need to be closed asynchronous */ // 关闭那些需要异步关闭的客户端 freeclientsinasyncfreequeue(); /* clear the paused clients flag if needed. */ clientsarepaused(); /* don't check return value, just use the side effect. */ /* replication cron function -- used to reconnect to master and * to detect transfer failures. */ // 复制函数 // 重连接主服务器、向主服务器发送 ack 、判断数据发送失败情况、断开本服务器超时的从服务器,等等 run_with_period(1000) replicationcron(); /* run the redis cluster cron. */ // 如果服务器运行在集群模式下,那么执行集群操作 run_with_period(100) { if (server.cluster_enabled) clustercron(); } /* run the sentinel timer if we are in sentinel mode. */ // 如果服务器运行在 sentinel 模式下,那么执行 sentinel 的主函数 run_with_period(100) { if (server.sentinel_mode) sentineltimer(); } /* cleanup expired migrate cached sockets. */ // 集群。。。todo run_with_period(1000) { migrateclosetimedoutsockets(); } // 增加 loop 计数器 server.cronloops++; return 1000/server.hz;}
3. 初始化服务器3.1 服务器状态结构redis.h/redisserver结构,服务器状态:
struct redisserver { /* general */ // 配置文件的绝对路径 char *configfile; /* absolute config file path, or null */ // servercron() 每秒调用的次数 int hz; /* servercron() calls frequency in hertz */ // 数据库 redisdb *db; // 命令表(受到 rename 配置选项的作用) dict *commands; /* command table */ // 命令表(无 rename 配置选项的作用) dict *orig_commands; /* command table before command renaming. */ // 事件状态 aeeventloop *el; // 最近一次使用时钟 unsigned lruclock:redis_lru_bits; /* clock for lru eviction */ // 关闭服务器的标识 int shutdown_asap; /* shutdown needed asap */ // 在执行 servercron() 时进行渐进式 rehash int activerehashing; /* incremental rehash in servercron() */ // 是否设置了密码 char *requirepass; /* pass for auth command, or null */ // pid 文件 char *pidfile; /* pid file path */ // 架构类型 int arch_bits; /* 32 or 64 depending on sizeof(long) */ // servercron() 函数的运行次数计数器 int cronloops; /* number of times the cron function run */ // 本服务器的 run id char runid[redis_run_id_size+1]; /* id always different at every exec. */ // 服务器是否运行在 sentinel 模式 int sentinel_mode; /* true if this instance is a sentinel. */ /* networking */ // tcp 监听端口 int port; /* tcp listening port */ int tcp_backlog; /* tcp listen() backlog */ // 地址 char *bindaddr[redis_bindaddr_max]; /* addresses we should bind to */ // 地址数量 int bindaddr_count; /* number of addresses in server.bindaddr[] */ // unix 套接字 char *unixsocket; /* unix socket path */ mode_t unixsocketperm; /* unix socket permission */ // 描述符 int ipfd[redis_bindaddr_max]; /* tcp socket file descriptors */ // 描述符数量 int ipfd_count; /* used slots in ipfd[] */ // unix 套接字文件描述符 int sofd; /* unix socket file descriptor */ int cfd[redis_bindaddr_max];/* cluster bus listening socket */ int cfd_count; /* used slots in cfd[] */ // 一个链表,保存了所有客户端状态结构 list *clients; /* list of active clients */ // 链表,保存了所有待关闭的客户端 list *clients_to_close; /* clients to close asynchronously */ // 链表,保存了所有从服务器,以及所有监视器 list *slaves, *monitors; /* list of slaves and monitors */ // 服务器的当前客户端,仅用于崩溃报告 redisclient *current_client; /* current client, only used on crash report */ int clients_paused; /* true if clients are currently paused */ mstime_t clients_pause_end_time; /* time when we undo clients_paused */ // 网络错误 char neterr[anet_err_len]; /* error buffer for anet.c */ // migrate 缓存 dict *migrate_cached_sockets;/* migrate cached sockets */ /* rdb / aof loading information */ // 这个值为真时,表示服务器正在进行载入 int loading; /* we are loading data from disk if true */ // 正在载入的数据的大小 off_t loading_total_bytes; // 已载入数据的大小 off_t loading_loaded_bytes; // 开始进行载入的时间 time_t loading_start_time; off_t loading_process_events_interval_bytes; /* fast pointers to often looked up command */ // 常用命令的快捷连接 struct rediscommand *delcommand, *multicommand, *lpushcommand, *lpopcommand, *rpopcommand; /* fields used only for stats */ // 服务器启动时间 time_t stat_starttime; /* server start time */ // 已处理命令的数量 long long stat_numcommands; /* number of processed commands */ // 服务器接到的连接请求数量 long long stat_numconnections; /* number of connections received */ // 已过期的键数量 long long stat_expiredkeys; /* number of expired keys */ // 因为回收内存而被释放的过期键的数量 long long stat_evictedkeys; /* number of evicted keys (maxmemory) */ // 成功查找键的次数 long long stat_keyspace_hits; /* number of successful lookups of keys */ // 查找键失败的次数 long long stat_keyspace_misses; /* number of failed lookups of keys */ // 已使用内存峰值 size_t stat_peak_memory; /* max used memory record */ // 最后一次执行 fork() 时消耗的时间 long long stat_fork_time; /* time needed to perform latest fork() */ // 服务器因为客户端数量过多而拒绝客户端连接的次数 long long stat_rejected_conn; /* clients rejected because of maxclients */ // 执行 full sync 的次数 long long stat_sync_full; /* number of full resyncs with slaves. */ // psync 成功执行的次数 long long stat_sync_partial_ok; /* number of accepted psync requests. */ // psync 执行失败的次数 long long stat_sync_partial_err;/* number of unaccepted psync requests. */ /* slowlog */ // 保存了所有慢查询日志的链表 list *slowlog; /* slowlog list of commands */ // 下一条慢查询日志的 id long long slowlog_entry_id; /* slowlog current entry id */ // 服务器配置 slowlog-log-slower-than 选项的值 long long slowlog_log_slower_than; /* slowlog time limit (to get logged) */ // 服务器配置 slowlog-max-len 选项的值 unsigned long slowlog_max_len; /* slowlog max number of items logged */ size_t resident_set_size; /* rss sampled in servercron(). */ /* the following two are used to track instantaneous load in terms * of operations per second. */ // 最后一次进行抽样的时间 long long ops_sec_last_sample_time; /* timestamp of last sample (in ms) */ // 最后一次抽样时,服务器已执行命令的数量 long long ops_sec_last_sample_ops; /* numcommands in last sample */ // 抽样结果 long long ops_sec_samples[redis_ops_sec_samples]; // 数组索引,用于保存抽样结果,并在需要时回绕到 0 int ops_sec_idx; /* configuration */ // 日志可见性 int verbosity; /* loglevel in redis.conf */ // 客户端最大空转时间 int maxidletime; /* client timeout in seconds */ // 是否开启 so_keepalive 选项 int tcpkeepalive; /* set so_keepalive if non-zero. */ int active_expire_enabled; /* can be disabled for testing purposes. */ size_t client_max_querybuf_len; /* limit for client query buffer length */ int dbnum; /* total number of configured dbs */ int daemonize; /* true if running as a daemon */ // 客户端输出缓冲区大小限制 // 数组的元素有 redis_client_limit_num_classes 个 // 每个代表一类客户端:普通、从服务器、pubsub,诸如此类 clientbufferlimitsconfig client_obuf_limits[redis_client_limit_num_classes]; /* aof persistence */ // aof 状态(开启/关闭/可写) int aof_state; /* redis_aof_(on|off|wait_rewrite) */ // 所使用的 fsync 策略(每个写入/每秒/从不) int aof_fsync; /* kind of fsync() policy */ char *aof_filename; /* name of the aof file */ int aof_no_fsync_on_rewrite; /* don't fsync if a rewrite is in prog. */ int aof_rewrite_perc; /* rewrite aof if % growth is > m and... */ off_t aof_rewrite_min_size; /* the aof file is at least n bytes. */ // 最后一次执行 bgrewriteaof 时, aof 文件的大小 off_t aof_rewrite_base_size; /* aof size on latest startup or rewrite. */ // aof 文件的当前字节大小 off_t aof_current_size; /* aof current size. */ int aof_rewrite_scheduled; /* rewrite once bgsave terminates. */ // 负责进行 aof 重写的子进程 id pid_t aof_child_pid; /* pid if rewriting process */ // aof 重写缓存链表,链接着多个缓存块 list *aof_rewrite_buf_blocks; /* hold changes during an aof rewrite. */ // aof 缓冲区 sds aof_buf; /* aof buffer, written before entering the event loop */ // aof 文件的描述符 int aof_fd; /* file descriptor of currently selected aof file */ // aof 的当前目标数据库 int aof_selected_db; /* currently selected db in aof */ // 推迟 write 操作的时间 time_t aof_flush_postponed_start; /* unix time of postponed aof flush */ // 最后一直执行 fsync 的时间 time_t aof_last_fsync; /* unix time of last fsync() */ time_t aof_rewrite_time_last; /* time used by last aof rewrite run. */ // aof 重写的开始时间 time_t aof_rewrite_time_start; /* current aof rewrite start time. */ // 最后一次执行 bgrewriteaof 的结果 int aof_lastbgrewrite_status; /* redis_ok or redis_err */ // 记录 aof 的 write 操作被推迟了多少次 unsigned long aof_delayed_fsync; /* delayed aof fsync() counter */ // 指示是否需要每写入一定量的数据,就主动执行一次 fsync() int aof_rewrite_incremental_fsync;/* fsync incrementally while rewriting? */ int aof_last_write_status; /* redis_ok or redis_err */ int aof_last_write_errno; /* valid if aof_last_write_status is err */ /* rdb persistence */ // 自从上次 save 执行以来,数据库被修改的次数 long long dirty; /* changes to db from the last save */ // bgsave 执行前的数据库被修改次数 long long dirty_before_bgsave; /* used to restore dirty on failed bgsave */ // 负责执行 bgsave 的子进程的 id // 没在执行 bgsave 时,设为 -1 pid_t rdb_child_pid; /* pid of rdb saving child */ struct saveparam *saveparams; /* save points array for rdb */ int saveparamslen; /* number of saving points */ char *rdb_filename; /* name of rdb file */ int rdb_compression; /* use compression in rdb? */ int rdb_checksum; /* use rdb checksum? */ // 最后一次完成 save 的时间 time_t lastsave; /* unix time of last successful save */ // 最后一次尝试执行 bgsave 的时间 time_t lastbgsave_try; /* unix time of last attempted bgsave */ // 最近一次 bgsave 执行耗费的时间 time_t rdb_save_time_last; /* time used by last rdb save run. */ // 数据库最近一次开始执行 bgsave 的时间 time_t rdb_save_time_start; /* current rdb save start time. */ // 最后一次执行 save 的状态 int lastbgsave_status; /* redis_ok or redis_err */ int stop_writes_on_bgsave_err; /* don't allow writes if can't bgsave */ /* propagation of commands in aof / replication */ redisoparray also_propagate; /* additional command to propagate. */ /* logging */ char *logfile; /* path of log file */ int syslog_enabled; /* is syslog enabled? */ char *syslog_ident; /* syslog ident */ int syslog_facility; /* syslog facility */ /* replication (master) */ int slaveseldb; /* last selected db in replication output */ // 全局复制偏移量(一个累计值) long long master_repl_offset; /* global replication offset */ // 主服务器发送 ping 的频率 int repl_ping_slave_period; /* master pings the slave every n seconds */ // backlog 本身 char *repl_backlog; /* replication backlog for partial syncs */ // backlog 的长度 long long repl_backlog_size; /* backlog circular buffer size */ // backlog 中数据的长度 long long repl_backlog_histlen; /* backlog actual data length */ // backlog 的当前索引 long long repl_backlog_idx; /* backlog circular buffer current offset */ // backlog 中可以被还原的第一个字节的偏移量 long long repl_backlog_off; /* replication offset of first byte in the backlog buffer. */ // backlog 的过期时间 time_t repl_backlog_time_limit; /* time without slaves after the backlog gets released. */ // 距离上一次有从服务器的时间 time_t repl_no_slaves_since; /* we have no slaves since that time. only valid if server.slaves len is 0. */ // 是否开启最小数量从服务器写入功能 int repl_min_slaves_to_write; /* min number of slaves to write. */ // 定义最小数量从服务器的最大延迟值 int repl_min_slaves_max_lag; /* max lag of slaves to write. */ // 延迟良好的从服务器的数量 int repl_good_slaves_count; /* number of slaves with lag master sync socket */ // 保存 rdb 文件的临时文件的描述符 int repl_transfer_fd; /* slave -> master sync temp file descriptor */ // 保存 rdb 文件的临时文件名字 char *repl_transfer_tmpfile; /* slave-> master sync temp file name */ // 最近一次读入 rdb 内容的时间 time_t repl_transfer_lastio; /* unix time of the latest read, for timeout */ int repl_serve_stale_data; /* serve stale data when link is down? */ // 是否只读从服务器? int repl_slave_ro; /* slave is read only? */ // 连接断开的时长 time_t repl_down_since; /* unix time at which link with master went down */ // 是否要在 sync 之后关闭 nodelay ? int repl_disable_tcp_nodelay; /* disable tcp_nodelay after sync? */ // 从服务器优先级 int slave_priority; /* reported in info and used by sentinel. */ // 本服务器(从服务器)当前主服务器的 run id char repl_master_runid[redis_run_id_size+1]; /* master run id for psync. */ // 初始化偏移量 long long repl_master_initial_offset; /* master psync offset. */ /* replication script cache. */ // 复制脚本缓存 // 字典 dict *repl_scriptcache_dict; /* sha1 all slaves are aware of. */ // fifo 队列 list *repl_scriptcache_fifo; /* first in, first out lru eviction. */ // 缓存的大小 int repl_scriptcache_size; /* max number of elements. */ /* synchronous replication. */ list *clients_waiting_acks; /* clients waiting in wait command. */ int get_ack_from_slaves; /* if true we send replconf getack. */ /* limits */ int maxclients; /* max number of simultaneous clients */ unsigned long long maxmemory; /* max number of memory bytes to use */ int maxmemory_policy; /* policy for key eviction */ int maxmemory_samples; /* pricision of random sampling */ /* blocked clients */ unsigned int bpop_blocked_clients; /* number of clients blocked by lists */ list *unblocked_clients; /* list of clients to unblock before next loop */ list *ready_keys; /* list of readylist structures for blpop & co */ /* sort parameters - qsort_r() is only available under bsd so we * have to take this state global, in order to pass it to sortcompare() */ int sort_desc; int sort_alpha; int sort_bypattern; int sort_store; /* zip structure config, see redis.conf for more information */ size_t hash_max_ziplist_entries; size_t hash_max_ziplist_value; size_t list_max_ziplist_entries; size_t list_max_ziplist_value; size_t set_max_intset_entries; size_t zset_max_ziplist_entries; size_t zset_max_ziplist_value; size_t hll_sparse_max_bytes; time_t unixtime; /* unix time sampled every cron cycle. */ long long mstime; /* like 'unixtime' but with milliseconds resolution. */ /* pubsub */ // 字典,键为频道,值为链表 // 链表中保存了所有订阅某个频道的客户端 // 新客户端总是被添加到链表的表尾 dict *pubsub_channels; /* map channels to list of subscribed clients */ // 这个链表记录了客户端订阅的所有模式的名字 list *pubsub_patterns; /* a list of pubsub_patterns */ int notify_keyspace_events; /* events to propagate via pub/sub. this is an xor of redis_notify... flags. */ /* cluster */ int cluster_enabled; /* is cluster enabled? */ mstime_t cluster_node_timeout; /* cluster node timeout. */ char *cluster_configfile; /* cluster auto-generated config file name. */ struct clusterstate *cluster; /* state of the cluster */ int cluster_migration_barrier; /* cluster replicas migration barrier. */ /* scripting */ // lua 环境 lua_state *lua; /* the lua interpreter. we use just one for all clients */ // 复制执行 lua 脚本中的 redis 命令的伪客户端 redisclient *lua_client; /* the fake client to query redis from lua */ // 当前正在执行 eval 命令的客户端,如果没有就是 null redisclient *lua_caller; /* the client running eval right now, or null */ // 一个字典,值为 lua 脚本,键为脚本的 sha1 校验和 dict *lua_scripts; /* a dictionary of sha1 -> lua scripts */ // lua 脚本的执行时限 mstime_t lua_time_limit; /* script timeout in milliseconds */ // 脚本开始执行的时间 mstime_t lua_time_start; /* start time of script, milliseconds time */ // 脚本是否执行过写命令 int lua_write_dirty; /* true if a write command was called during the execution of the current script. */ // 脚本是否执行过带有随机性质的命令 int lua_random_dirty; /* true if a random command was called during the execution of the current script. */ // 脚本是否超时 int lua_timedout; /* true if we reached the time limit for script execution. */ // 是否要杀死脚本 int lua_kill; /* kill the script if true. */ /* assert & bug reporting */ char *assert_failed; char *assert_file; int assert_line; int bug_report_start; /* true if bug report header was already logged. */ int watchdog_period; /* software watchdog period in ms. 0 = off */};
===========================================
初始化服务器的第一步:创建一个struct redisserver 类型的实例变量server作为服务器状态,并为各个属性设置默认值。
//redis.hextern struct redisserver server;
初始化server变量由redis.c/initserverconfig函数完成:
void initserverconfig() { int j; // 服务器状态 // 设置服务器的运行 id getrandomhexchars(server.runid,redis_run_id_size); // 设置默认配置文件路径 server.configfile = null; // 设置默认服务器频率 server.hz = redis_default_hz; // 为运行 id 加上结尾字符 server.runid[redis_run_id_size] = '\0'; // 设置服务器的运行架构 server.arch_bits = (sizeof(long) == 8) ? 64 : 32; // 设置默认服务器端口号 server.port = redis_serverport; server.tcp_backlog = redis_tcp_backlog; server.bindaddr_count = 0; server.unixsocket = null; server.unixsocketperm = redis_default_unix_socket_perm; server.ipfd_count = 0; server.sofd = -1; server.dbnum = redis_default_dbnum; server.verbosity = redis_default_verbosity; server.maxidletime = redis_maxidletime; server.tcpkeepalive = redis_default_tcp_keepalive; server.active_expire_enabled = 1; server.client_max_querybuf_len = redis_max_querybuf_len; server.saveparams = null; server.loading = 0; server.logfile = zstrdup(redis_default_logfile); server.syslog_enabled = redis_default_syslog_enabled; server.syslog_ident = zstrdup(redis_default_syslog_ident); server.syslog_facility = log_local0; server.daemonize = redis_default_daemonize; server.aof_state = redis_aof_off; server.aof_fsync = redis_default_aof_fsync; server.aof_no_fsync_on_rewrite = redis_default_aof_no_fsync_on_rewrite; server.aof_rewrite_perc = redis_aof_rewrite_perc; server.aof_rewrite_min_size = redis_aof_rewrite_min_size; server.aof_rewrite_base_size = 0; server.aof_rewrite_scheduled = 0; server.aof_last_fsync = time(null); server.aof_rewrite_time_last = -1; server.aof_rewrite_time_start = -1; server.aof_lastbgrewrite_status = redis_ok; server.aof_delayed_fsync = 0; server.aof_fd = -1; server.aof_selected_db = -1; /* make sure the first time will not match */ server.aof_flush_postponed_start = 0; server.aof_rewrite_incremental_fsync = redis_default_aof_rewrite_incremental_fsync; server.pidfile = zstrdup(redis_default_pid_file); server.rdb_filename = zstrdup(redis_default_rdb_filename); server.aof_filename = zstrdup(redis_default_aof_filename); server.requirepass = null; server.rdb_compression = redis_default_rdb_compression; server.rdb_checksum = redis_default_rdb_checksum; server.stop_writes_on_bgsave_err = redis_default_stop_writes_on_bgsave_error