引言:
- 上一篇 07 命令表与命令查找 讲的是命令怎么被找到。
这一篇接着往下走:找到之后呢?- 从
GET mykey这五个字节进来到$5\r\nhello\r\n出去,中间一共有多少个函数?
哪一个是「真正干活」的?processCommand里有十几道if,它们分别拦什么?顺序有讲究吗?- 一条命令被拒的时候,回的是哪个错误串?
-OOM、-LOADING、-BUSY、-READONLY各自在什么条件下出现?- 命令执行完,Redis 记了哪些账?
INFO commandstats、SLOWLOG、LATENCY、热点统计分别记在哪一步?server.dirty这个计数器谁在加?为什么它决定了命令要不要进 AOF 和复制流?- 一个已经过期但还没被回收的 key,是在哪一步被删掉的?
- MULTI 里的命令是真的执行了,还是只是排队?
+QUEUED是什么时候回给客户端的?本文不讨论:命令表本身怎么造(第 07 章)、字节怎么从 socket 读出来并解析成 RESP(第 09 章)、
事件循环怎么调度(第 10 章)、AOF 与复制流的具体格式(第 11、12 章)。
本文只讲一件事:一条命令被找到之后,它走完了哪些关卡、做完了哪些事。本文所有行号基于
/work/ai/cwork/redis,分支unstable,git describe --tags=8.12-m02-int-184-gff28c55fc,HEAD =ff28c55f,
核对时间:2026-12-04。版本号为什么是
255.255.255:src/version.h:1是 unstable 分支的占位符,
真实发布号在切稳定分支时人工改写。认准git describe --tags的结果,
别拿INFO里的redis_version当版本。
8.1 一条命令的旅程:全景图
先把整条路铺开,再一段一段进去看。
从客户端发出 GET mykey 开始,到客户端收到回复,Redis 内部经过的是这样一条链:
| 阶段 | 在哪 | 干什么 |
|---|---|---|
| ① 读 & 解析 | src/networking.c:3848 processInputBuffer |
把 socket 里的字节切成一条条 pendingCommand |
| ② 预处理 | src/server.c:4705 preprocessCommand |
提前把命令查出来、key 抽出来、槽位算出来 |
| ③ 关卡 | src/server.c:4761 processCommand |
十几道检查,任何一道不过就回错误串 |
| ④ 执行 | src/server.c:4223 call |
调 c->cmd->proc(c),命令在这里真正跑 |
| ⑤ 记账 | src/server.c:4376 起 |
延迟、慢日志、MONITOR、commandstats、热点统计 |
| ⑥ 传播 | src/server.c:4444 |
脏了就进 AOF 和复制流 |
| ⑦ 收尾 | src/server.c:4598 afterCommandEx |
刷 tracking 失效消息、合推送消息、跑断言 |
| ⑧ 回包 | src/networking.c:649 addReply |
拼进输出缓冲,等事件循环写回 socket |
这棵树最值得注意的是 ②:在 7.x 里,命令查找发生在 processCommand 里;
这棵树把它提到了解析阶段,放进 preprocessCommand。原因是 IO 线程要并行预解析
多条命令,主线程只负责执行 —— 查命令、抽 key 这些纯读操作放在 IO 线程里做,
主线程就不用重复做一遍。下面 8.2 会讲这个。
另外一处结构性变化是 pendingCommand。7.x 里一条命令的参数直接躺在 c->argv 上;
这棵树给每条待执行命令发了一个独立的 pendingCommand 结构(src/server.h:2945),
排成队列(c->pending_cmds)等着被消费。
8.2 阶段一:解析与预处理
8.2.1 解析:一批命令排队等执行
processInputBuffer 是入口。它不是「解析一条、执行一条」,而是先攒一批:
// src/networking.c:3862-3867
const int lookahead = authRequired(c) ? 1 : server.lookahead;
/* Keep processing while there is something in the input buffer */
while ((c->querybuf && c->qb_pos < sdslen(c->querybuf)) ||
c->pending_cmds.ready_len > 0)
{
lookahead 是「最多预解析几条命令」。未认证的连接被限制成 1,注释说得很清楚:AUTH 会影响后续命令的处理方式,多解析几条可能解析错(src/networking.c:3857-3861)。
真正的解析循环在这里:
// src/networking.c:3896-3946
while (parse_more && c->pending_cmds.ready_len < lookahead &&
c->querybuf && c->qb_pos < sdslen(c->querybuf))
{
/* Determine request type when unknown. */
if (!c->reqtype) {
if (c->querybuf[c->qb_pos] == '*') {
c->reqtype = PROTO_REQ_MULTIBULK;
} else {
c->reqtype = PROTO_REQ_INLINE;
}
}
pendingCommand *pcmd = NULL;
if (c->reqtype == PROTO_REQ_INLINE) {
pcmd = acquirePendingCommand();
if (processInlineBuffer(c, pcmd) == C_ERR && !pcmd->read_error) {
/* If it fails but there are no errors, it means that it might just be
* that the desired content cannot be parsed. At this point, we exit and wait for the next time. */
freePendingCommand(c, pcmd);
break;
}
} else if (c->reqtype == PROTO_REQ_MULTIBULK) {
int incomplete = (c->pending_cmds.len != c->pending_cmds.ready_len);
if (unlikely(incomplete)) {
pcmd = popPendingCommandFromTail(&c->pending_cmds);
} else {
pcmd = acquirePendingCommand();
}
if (processMultibulkBuffer(c, pcmd) == C_ERR && !pcmd->read_error) {
/* If it fails but there are no errors, it means that it might just be
* that the desired content cannot be parsed. At this point, we exit and wait for the next time. */
freePendingCommand(c, pcmd);
break;
}
} else {
serverPanic("Unknown request type");
}
addPendingCommand(&c->pending_cmds, pcmd);
if (unlikely(pcmd->read_error || (pcmd->flags & PENDING_CMD_FLAG_INCOMPLETE)))
break;
if (c->running_tid == IOTHREAD_MAIN_THREAD_ID)
pcmd->reploff = c->read_reploff - sdslen(c->querybuf) + c->qb_pos;
else
pcmd->reploff = c->io_read_reploff - sdslen(c->querybuf) + c->qb_pos;
preprocessCommand(c, pcmd);
resetClientQbufState(c);
}
三个细节值得停下来看:
pcmd可能不是新分配的。如果上一次解析留下的命令是不完整的
(incomplete),这次是把队尾那个拿出来接着解析,而不是新建一个。
也就是说:一条命令的参数可以被多次 socket 读取拼出来。read_error是个枚举而不是布尔。CLIENT_READ_COMMAND_NOT_FOUND= 14、CLIENT_READ_BAD_ARITY= 15(src/server.h:528-529)。解析阶段就能判定
「命令不存在」和「参数个数不对」,这比 7.x 提前了一大截。reploff分了两份:c->read_reploff给主线程用,c->io_read_reploff给 IO 线程用。
这是第 10 章 IO 多线程那套设计的痕迹 —— 主线程和 IO 线程各有一套读取偏移量。
8.2.2 pendingCommand:一条命令的容器
// src/server.h:2945-2961
struct pendingCommand {
int argc; /* Num of arguments of current command. */
int argv_len; /* Size of argv array (may be more than argc) */
robj **argv; /* Arguments of current command. */
size_t argv_len_sum; /* Sum of lengths of objects in argv list. */
unsigned long long input_bytes;
struct redisCommand *cmd;
getKeysResult keys_result;
long long reploff; /* c->reploff should be set to this value when the command is processed */
int flags;
int slot; /* The slot the command is executing against. Set to INVALID_CLUSTER_SLOT
* if no slot is being used or if the command has a cross slot error */
uint8_t read_error;
struct pendingCommand *next;
struct pendingCommand *prev;
};
cmd、keys_result、slot 三项是预处理产物 —— 解析完就已经算好了,
执行的时候直接拿。这就是「IO 线程预解析」能省下主线程时间的原因。
它是双向链表(next / prev),因为「队尾那条可能不完整,要拿出来接着解析」
需要从尾部摘除(popPendingCommandFromTail),而「取下一条执行」需要从头取
(c->pending_cmds.head)。
8.2.3 预处理:命令、key、槽位
// src/server.c:4705-4736
void preprocessCommand(client *c, pendingCommand *pcmd) {
pcmd->cmd = NULL;
pcmd->slot = INVALID_CLUSTER_SLOT;
pcmd->read_error = 0;
pcmd->flags &= ~PENDING_CMD_KEYS_RESULT_VALID;
pcmd->flags |= PENDING_CMD_FLAG_PREPROCESSED;
getKeysFreeResult(&pcmd->keys_result);
pcmd->keys_result = (getKeysResult)GETKEYS_RESULT_INIT;
if (pcmd->argc == 0)
return;
/* Check if we can reuse the previous command instead of looking it up.
* The previous command is either the penultimate pending command (if it exists), or c->lastcmd. */
struct redisCommand *last_cmd = pcmd->prev ? pcmd->prev->cmd : c->lastcmd;
if (isCommandReusable(last_cmd, pcmd->argv, pcmd->argc))
pcmd->cmd = last_cmd;
else
pcmd->cmd = lookupCommand(pcmd->argv, pcmd->argc);
if (!pcmd->cmd) {
pcmd->read_error = CLIENT_READ_COMMAND_NOT_FOUND;
return;
}
if ((pcmd->cmd->arity > 0 && pcmd->cmd->arity != pcmd->argc) ||
(pcmd->argc < -pcmd->cmd->arity))
{
pcmd->read_error = CLIENT_READ_BAD_ARITY;
return;
}
isCommandReusable 是这里最实用的一招:
// src/server.c:111-118
static inline int isCommandReusable(struct redisCommand *cmd, robj **argv, int argc) {
if (cmd == NULL || cmd->subcommands_dict != NULL) return 0;
if (cmd->parent == NULL)
return strcasecmp(cmd->fullname, argv[0]->ptr) == 0;
return argc >= 2 &&
strcasecmp(cmd->parent->fullname, argv[0]->ptr) == 0 &&
strcasecmp(cmd->declared_name, argv[1]->ptr) == 0;
}
意思是:如果新命令的名字和上一条一样,就不用再查一次表。
管道里连续 1000 条 GET,只需要查一次表。这在 7.x 里的对应物是c->lastcmd 的复用逻辑,但 7.x 是在 processCommand 里做的,而且只复用一条;
这棵树改成在解析阶段复用,且能复用倒数第二条(因为队尾那条可能还没解析完)。
注意 isCommandReusable 对带子命令的命令直接返回 0(cmd->subcommands_dict != NULL)。
因为 OBJECT ENCODING 的判定要看 argv[1],光比 argv[0] 不够 —— 与其写两套逻辑,
不如老老实实查表。
8.2.4 消费:把队头那条搬到 c->argv 上
解析够了不等于能执行。执行前要把 pendingCommand 的字段搬回老的 c->argv / c->argc,
这样后面所有读 c->argv 的老代码都不用改:
// src/networking.c:3957-3984
/* Try to consume the next ready command from the pending command list. */
if (!c->pending_cmds.ready_len)
break;
pendingCommand *curcmd = c->pending_cmds.head;
/* We populate the old client fields so we don't have to modify all existing logic to work with pendingCommands */
c->argc = curcmd->argc;
c->argv = curcmd->argv;
c->argv_len = curcmd->argv_len;
c->net_input_bytes_curr_cmd += curcmd->input_bytes;
c->reploff_next = curcmd->reploff;
c->slot = curcmd->slot;
c->lookedcmd = curcmd->cmd;
c->read_error = curcmd->read_error;
c->current_pending_cmd = curcmd;
/* Prefetch the command only when more commands have been parsed and we
* are in the main thread. If running in an IO thread, prefetch will be
* deferred until the client is processed by the main thread. Skip prefetch
* if there are too few commands to avoid meaningless prefetching. */
if (parse_more && c->running_tid == IOTHREAD_MAIN_THREAD_ID &&
c->pending_cmds.ready_len > 1)
{
/* Prefetch the commands. */
resetCommandsBatch();
addCommandToBatch(c);
prefetchCommands();
}
c->lookedcmd = curcmd->cmd 这一行接回了第 07 章:processCommand 里struct redisCommand *cmd = c->lookedcmd; —— 命令已经在解析阶段查好了,processCommand 直接取。这就是为什么 processCommand 里的查找逻辑长这样:
// src/server.c:4794-4813
if (!client_reprocessing_command) {
/* check if we can reuse the last command instead of looking up if we already have that info */
struct redisCommand *cmd = c->lookedcmd;
/* The command may have been modified by modules (e.g., in CommandFilters callbacks),
* so we need to look it up again. */
if (!cmd) {
if (isCommandReusable(c->lastcmd, c->argv, c->argc))
cmd = c->lastcmd;
else
cmd = lookupCommand(c->argv, c->argc);
}
if (!cmd) {
/* Handle possible security attacks. */
if (!strcasecmp(c->argv[0]->ptr,"host:") || !strcasecmp(c->argv[0]->ptr,"post")) {
securityWarningCommand(c);
return C_ERR;
}
}
c->lookedcmd 有值就直接用;但注释明说:模块可能改过命令(CommandFilters 回调),
所以「模块过滤器跑过之后要重新查一次」。这就是为什么 lookedcmd 是
「预解析的结果」,而 c->cmd 是「最终要执行的那个」—— 两个字段,各有用途。
8.3 阶段二:processCommand 的关卡
processCommand 从 src/server.c:4761 开始,到 :5145 结束,385 行。
绝大部分是检查。
8.3.1 关卡顺序
按代码里的实际顺序,命令要过的关卡是这样的:
| # | 关卡 | 位置 | 不过时回什么 |
|---|---|---|---|
| 1 | 模块命令过滤器 | src/server.c:4776-4779 |
模块自己决定 |
| 2 | 模块 yield 等待 | src/server.c:4783-4788 |
不回,客户端被挂起 |
| 3 | 命令存在 | src/server.c:4823-4826 |
unknown command 'xxx' |
| 4 | 参数个数 | src/server.c:4827-4830 |
wrong number of arguments |
| 5 | 受保护命令 | src/server.c:4834-4846 |
DEBUG command not allowed |
| 6 | 认证 | src/server.c:4867-4874 |
-NOAUTH |
| 7 | 事务内禁用 | src/server.c:4876-4879 |
Command not allowed inside a transaction |
| 8 | ACL | src/server.c:4884-4891 |
-NOPERM |
| 9 | 集群重定向 | src/server.c:4897-4917 |
-MOVED / -ASK |
| 10 | 客户端内存驱逐 | src/server.c:4937-4941 |
连接被关 |
| 11 | maxmemory / OOM | src/server.c:4962-4965 |
-OOM |
| 12 | 持久化磁盘错误 | src/server.c:4982-5007 |
-MISCONF |
| 13 | 副本数不足 | src/server.c:5011-5014 |
-NOREPLICAS |
| 14 | 只读副本 | src/server.c:5018-5024 |
-READONLY |
| 15 | 槽位迁移中 | src/server.c:5032-5044 |
主节点被挂起 |
| 16 | Pub/Sub 上下文 | src/server.c:5048-5063 |
Can't execute 'xxx' |
| 17 | 主链路断开 | src/server.c:5068-5074 |
-MASTERDOWN |
| 18 | 加载中 | src/server.c:5078-5087 |
-LOADING |
| 19 | 忙(脚本/模块) | src/server.c:5096-5107 |
-BUSY |
| 20 | 副本不许碰键空间 | src/server.c:5112-5115 |
Replica can't interact with the keyspace |
| 21 | 客户端暂停 | src/server.c:5119-5125 |
不回,客户端被挂起 |
顺序是有讲究的。举两个例子:
- 认证(6)在 ACL(8)之前:没认证的用户连用户是谁都不知道,ACL 无从谈起。
- 命令存在(3)在认证(6)之前:这条顺序有点反直觉 —— 意思是未认证的连接
也能看出「这个命令存不存在」。这是刻意的:客户端需要靠回错来区分
「命令拼错了」和「没登录」。但内部命令(CMD_INTERNAL)对非内部连接是隐形的:
// src/server.c:4815-4819
/* Internal commands seem unexistent to non-internal connections.
* masters and AOF loads are implicitly internal. */
if (cmd && (cmd->flags & CMD_INTERNAL) && !((c->flags & CLIENT_INTERNAL) || mustObeyClient(c))) {
cmd = NULL;
}
cmd = NULL 之后,就走「命令不存在」那条路了。
8.3.2 命令存在性与参数个数
这两关的实现很朴素:
// src/server.c:4670-4680
int commandCheckArity(struct redisCommand *cmd, int argc, sds *err) {
if ((cmd->arity > 0 && cmd->arity != argc) || (argc < -cmd->arity)) {
if (err) {
*err = sdsnew(NULL);
*err = sdscatprintf(*err, "wrong number of arguments for '%s' command", cmd->fullname);
}
return 0;
}
return 1;
}
arity 的语义:正数表示必须正好这么多参数;负数表示至少这么多个。-2 就是「至少 2 个」,所以 argc < -cmd->arity 即 argc < 2。
存在性检查稍微啰嗦一点,因为它要区分「未知命令」和「未知子命令」:
// src/server.c:4635-4650
if (isContainerCommandBySds(c->argv[0]->ptr)) {
/* If we can't find the command but argv[0] by itself is a command
* it means we're dealing with an invalid subcommand. Print Help. */
sds cmd = sdsnew((char *)c->argv[0]->ptr);
sdstoupper(cmd);
*err = sdsnew(NULL);
if (c->argc < 2) {
*err = sdscatprintf(*err, "missing subcommand. Try %s HELP.", cmd);
} else {
*err = sdscatprintf(*err, "unknown subcommand '%.128s'. Try %s HELP.",
(char *)c->argv[1]->ptr, cmd);
}
sdsfree(cmd);
} else {
「OBJECT 是个容器命令(它自己存在),但你给的子命令不存在」和
「FOOBAR 这条命令压根不存在」,回的是不同的串。前者提示 Try OBJECT HELP.。
8.3.3 flag 的运行时求值
接下来是一大段「这条命令算读还是算写」的判断:
// src/server.c:4849-4865
const uint64_t cmd_flags = getCommandFlags(c);
int is_read_command = (cmd_flags & CMD_READONLY) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_flags & CMD_READONLY));
int is_write_command = (cmd_flags & CMD_WRITE) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_flags & CMD_WRITE));
int is_denyoom_command = (cmd_flags & CMD_DENYOOM) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_flags & CMD_DENYOOM));
int is_denystale_command = !(cmd_flags & CMD_STALE) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_inv_flags & CMD_STALE));
int is_denyloading_command = !(cmd_flags & CMD_LOADING) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_inv_flags & CMD_LOADING));
int is_may_replicate_command = (cmd_flags & (CMD_WRITE | CMD_MAY_REPLICATE)) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_flags & (CMD_WRITE | CMD_MAY_REPLICATE)));
int is_deny_async_loading_command = (cmd_flags & CMD_NO_ASYNC_LOADING) ||
(c->cmd->proc == execCommand && (c->mstate.cmd_flags & CMD_NO_ASYNC_LOADING));
int obey_client = mustObeyClient(c);
每一行都有同一个模式:cmd_flags 上的判断,或者 —— 如果这是 EXEC ——
事务里累积的判断。c->mstate.cmd_flags 是队列里所有命令 flag 的并集,c->mstate.cmd_inv_flags 是反集(~cmd_flags 累积,见 src/multi.c:63)。
所以事务的整体属性是「里面最严格的那条命令说了算」:
只要有一条命令是写的,整个事务就是写的;只要有一条命令不允许在 OOM 下跑,
整个事务就不允许。
而 getCommandFlags 本身会动态改写 flag:
// src/server.c:4685-4697
uint64_t getCommandFlags(client *c) {
uint64_t cmd_flags = c->cmd->flags;
if (c->cmd->proc == fcallCommand || c->cmd->proc == fcallroCommand) {
cmd_flags = fcallGetCommandFlags(c, cmd_flags);
} else if (c->cmd->proc == evalCommand || c->cmd->proc == evalRoCommand ||
c->cmd->proc == evalShaCommand || c->cmd->proc == evalShaRoCommand)
{
cmd_flags = evalGetCommandFlags(c, cmd_flags);
}
return cmd_flags;
}
脚本自己声明的属性会覆盖命令表的静态属性。一个 EVAL 脚本如果声明了
「我只读」,那它跑起来就按只读对待(不进复制流、不受 OOM 拒绝)。
这个能力在 7.x 里是通过 redis.set_repl() 实现的,这棵树把它提升成了
脚本声明式的属性(src/eval.c:404、src/functions.c:609)—— 第 15 章会细讲。
8.3.4 认证、事务、ACL
// src/server.c:4867-4891
if (authRequired(c)) {
/* AUTH and HELLO and no auth commands are valid even in
* non-authenticated state. */
if (!(c->cmd->flags & CMD_NO_AUTH)) {
rejectCommand(c,shared.noautherr);
return C_OK;
}
}
if (c->flags & CLIENT_MULTI && c->cmd->flags & CMD_NO_MULTI) {
rejectCommandFormat(c,"Command not allowed inside a transaction");
return C_OK;
}
/* Check if the user can run this command according to the current
* ACLs. */
int acl_errpos;
int acl_retval = ACLCheckAllPerm(c,c->current_pending_cmd,&acl_errpos);
if (acl_retval != ACL_OK) {
addACLLogEntry(c,acl_retval,(c->flags & CLIENT_MULTI) ? ACL_LOG_CTX_MULTI : ACL_LOG_CTX_TOPLEVEL,acl_errpos,NULL,NULL);
sds msg = getAclErrorMessage(acl_retval, c->user, c->cmd, c->argv[acl_errpos]->ptr, 0);
rejectCommandFormat(c, "-NOPERM %s", msg);
sdsfree(msg);
return C_OK;
}
注意 ACL 检查传的是 c->current_pending_cmd,不是 c->argv。ACLCheckAllPerm(src/acl.c:1965)需要 pendingCommand 才能拿到
预解析出来的 keys_result —— ACL 检查要按命令实际碰到的 key 来判,
而不是按用户以为的 key 列表。这也是第 07 章 key_specs 的用武之地:
第 07 章说过 key_specs 不只给集群用,ACL 和集群重定向都靠它。
8.3.5 集群重定向
// src/server.c:4897-4917
if (server.cluster_enabled &&
!mustObeyClient(c) &&
!(!(c->cmd->flags&CMD_MOVABLE_KEYS) && c->cmd->key_specs_num == 0 &&
c->cmd->proc != execCommand))
{
int error_code;
getKeysResult *keyresult = getClientCachedKeyResult(c->current_pending_cmd);
clusterNode *n = getNodeByQuery(c,c->cmd,c->argv,c->argc,
&c->slot,keyresult,c->read_error,cmd_flags,&error_code);
if (n == NULL || !clusterNodeIsMyself(n)) {
if (c->cmd->proc == execCommand) {
discardTransaction(c);
} else {
flagTransaction(c);
}
clusterRedirectClient(c,n,c->slot,error_code);
resetClientCommandDuration(c);
c->cmd->rejected_calls++;
return C_OK;
}
}
getClientCachedKeyResult(c->current_pending_cmd) 取的是预处理阶段算好的 key。getNodeByQuery 拿着这些 key 算出目标节点;不是自己就重定向。
EXEC 的处理和普通命令不一样:普通命令只是 flagTransaction(c)(把事务标脏,EXEC 时整体 -EXECABORT),而 EXEC 自己被重定向时是 discardTransaction(c)
(直接丢弃事务)。原因很直观:EXEC 已经把所有命令打包在一起了,没法「标脏但不执行」。
8.3.6 内存关卡
// src/server.c:4934-4973
/* Disconnect some clients if total clients memory is too high. We do this
* before key eviction, after the last command was executed and consumed
* some client output buffer memory. */
evictClients();
if (server.current_client == NULL) {
/* If we evicted ourself then abort processing the command */
return C_ERR;
}
/* Handle the maxmemory directive.
*
* Note that we do not want to reclaim memory if we are here re-entering
* the event loop since there is a busy Lua script running in timeout
* condition, to avoid mixing the propagation of scripts with the
* propagation of DELs due to eviction. */
if (server.maxmemory && !isInsideYieldingLongCommand()) {
int out_of_memory = (performEvictions() == EVICT_FAIL);
/* performEvictions may evict keys, so we need flush pending tracking
* invalidation keys. If we don't do this, we may get an invalidation
* message after we perform operation on the key, where in fact this
* message belongs to the old value of the key before it gets evicted.*/
trackingHandlePendingKeyInvalidations();
/* performEvictions may flush slave output buffers. This may result
* in a slave, that may be the active client, to be freed. */
if (server.current_client == NULL) return C_ERR;
if (out_of_memory && is_denyoom_command) {
rejectCommand(c, shared.oomerr);
return C_OK;
}
/* Save out_of_memory result at command start, otherwise if we check OOM
* in the first write within script, memory used by lua stack and
* arguments might interfere. We need to save it for EXEC and module
* calls too, since these can call EVAL, but avoid saving it during an
* interrupted / yielding busy script / module. */
server.pre_command_oom_state = out_of_memory;
}
三个观察:
- OOM 判断是「先淘汰,淘汰不出来才算 OOM」。
performEvictions() == EVICT_FAIL意味着「内存还是超了,淘汰不出东西」。
只有这时才回-OOM。所以maxmemory满了不一定报错 —— 只要能淘汰掉就照样执行。 is_denyoom_command才受 OOM 影响。只读命令不受 OOM 限制。server.pre_command_oom_state把 OOM 状态存下来。因为命令执行中间
可能会再调别的命令(脚本里写内存),那时候再判断 OOM 会被脚本自己的栈内存干扰。
所以判断只在命令开始时做一次,结果存着复用。
8.3.7 持久化与复制关卡
// src/server.c:5009-5024
/* Don't accept write commands if there are not enough good slaves and
* user configured the min-slaves-to-write option. */
if (is_write_command && !checkGoodReplicasStatus()) {
rejectCommand(c, shared.noreplicaserr);
return C_OK;
}
/* Don't accept write commands if this is a read only slave. But
* accept write commands if this is our master. */
if (server.masterhost && server.repl_slave_ro &&
!obey_client &&
is_write_command)
{
rejectCommand(c, shared.roslaveerr);
return C_OK;
}
checkGoodReplicasStatus(src/replication.c:4887-4892)的逻辑是:
不是主节点、或者没配 min-replicas-to-write、或者 min-replicas-max-lag 是 0、
或者好副本数够了 —— 任何一条成立就算通过。
obey_client 是 mustObeyClient(c)(src/server.c:3815-3817):
// src/server.c:3815-3817
int mustObeyClient(client *c) {
return c->id == CLIENT_ID_AOF || c->flags & CLIENT_MASTER;
}
只有 AOF 加载客户端和主节点客户端能「违抗」这些检查。
主节点发来的写命令必须无条件执行 —— 否则复制就断了。
8.3.8 状态关卡:加载中、忙、副本
// src/server.c:5065-5087
/* Only allow commands with flag "t", such as INFO, REPLICAOF and so on,
* when replica-serve-stale-data is no and we are a replica with a broken
* link with master. */
if (server.masterhost && server.repl_state != REPL_STATE_CONNECTED &&
server.repl_serve_stale_data == 0 &&
is_denystale_command)
{
rejectCommand(c, shared.masterdownerr);
return C_OK;
}
/* Loading DB? Return an error if the command has not the
* CMD_LOADING flag. */
if (server.loading && !server.async_loading && is_denyloading_command) {
rejectCommand(c, shared.loadingerr);
return C_OK;
}
/* During async-loading, block certain commands. */
if (server.async_loading && is_deny_async_loading_command) {
rejectCommand(c,shared.loadingerr);
return C_OK;
}
is_denystale_command 的定义是 !(cmd_flags & CMD_STALE) —— 默认拒绝,显式开洞。
带 CMD_STALE 的命令(INFO、REPLICAOF 这些)在主链路断开时仍然允许执行。
这是运维需求:副本断连时你得能上去查状态、改配置。
同理 is_denyloading_command = !(cmd_flags & CMD_LOADING) —— 默认拒绝。
加载 RDB / AOF 期间,只有显式带 CMD_LOADING 的命令能跑。
「默认拒绝」这个设计值得记一下:安全相关的能力一律默认关闭、
显式开启。比「默认开启、显式关闭」要安全得多。
8.3.9 事务分支:排队还是执行
关卡全过,就到了分岔口:
// src/server.c:5127-5145
/* Exec the command */
if (c->flags & CLIENT_MULTI &&
c->cmd->proc != execCommand &&
c->cmd->proc != discardCommand &&
c->cmd->proc != multiCommand &&
c->cmd->proc != watchCommand &&
c->cmd->proc != quitCommand &&
c->cmd->proc != resetCommand)
{
queueMultiCommand(c, cmd_flags);
addReply(c,shared.queued);
} else {
int flags = CMD_CALL_FULL;
call(c,flags);
if (listLength(server.ready_keys) && !isInsideYieldingLongCommand())
handleClientsBlockedOnKeys();
}
return C_OK;
}
MULTI 之后、且不是 EXEC/DISCARD/MULTI/WATCH/QUIT/RESET 的命令,
一律排队,不执行。回的是 +QUEUED(src/server.c:2276)。
注意这段代码的位置:它在所有关卡之后。也就是说 MULTI 里的命令也要过全部关卡
(认证、ACL、集群重定向、只读副本……)。这不奇怪:MULTI 和 EXEC 之间的命令
如果越权,Redis 会在排队那一刻就拒绝,并且把整个事务标脏。
排队本身:
// src/multi.c:35-75
void queueMultiCommand(client *c, uint64_t cmd_flags) {
/* No sense to waste memory if the transaction is already aborted.
* this is useful in case client sends these in a pipeline, or doesn't
* bother to read previous responses and didn't notice the multi was already
* aborted. */
if (c->flags & (CLIENT_DIRTY_CAS|CLIENT_DIRTY_EXEC))
return;
if (c->mstate.count == 0) {
/* If a client is using multi/exec, assuming it is used to execute at least
* two commands. Hence, creating by default size of 2. */
c->mstate.commands = zmalloc(sizeof(pendingCommand*)*2);
c->mstate.alloc_count = 2;
}
if (c->mstate.count == c->mstate.alloc_count) {
c->mstate.alloc_count = c->mstate.alloc_count < INT_MAX/2 ? c->mstate.alloc_count*2 : INT_MAX;
c->mstate.commands = zrealloc(c->mstate.commands, sizeof(pendingCommand*)*(c->mstate.alloc_count));
}
/* Move the pending command into the multi-state.
* We leave the empty list node in 'pending_cmds' for freeClientPendingCommands to clean up
* later, but set the value to NULL to indicate it has been moved out and should not be freed. */
pendingCommand *pcmd = popPendingCommandFromHead(&c->pending_cmds);
c->current_pending_cmd = NULL;
pendingCommand **mc = c->mstate.commands + c->mstate.count;
*mc = pcmd;
c->mstate.count++;
c->mstate.cmd_flags |= cmd_flags;
c->mstate.cmd_inv_flags |= ~cmd_flags;
c->mstate.argv_len_sums += (*mc)->argv_len_sum;
c->all_argv_len_sum -= (*mc)->argv_len_sum;
(*mc)->argv_len_sum = 0; /* This is no longer tracked through all_argv_len_sum, so we don't want */
/* to subtract it from there later. */
/* Reset the client's args since we moved them into the mstate and shouldn't
* reference them from 'c' anymore. */
c->argv = NULL;
c->argc = 0;
c->argv_len = 0;
}
三处细节:
- 事务已脏就直接返回 —— 不再往队列里塞(省内存)。
cmd_flags |= cmd_flags(并集)与cmd_inv_flags |= ~cmd_flags(反集并集)
同时维护 —— 这就是 8.3.3 里「整个事务取最严格属性」的来源。- 初始容量是 2,注释说「用 multi/exec 的人至少会执行两条命令」。
扩容是翻倍。
8.4 阶段三:call() —— 真正干活的地方
processCommand 前面 300 多行都是检查,call() 才是执行。
它从 src/server.c:4223 开始。
8.4.1 快照与清理
// src/server.c:4223-4242
void call(client *c, int flags) {
long long dirty;
uint64_t client_old_flags = c->flags;
struct redisCommand *real_cmd = c->realcmd;
client *prev_client = server.executing_client;
server.executing_client = c;
/* When call() is issued during loading the AOF we don't want commands called
* from module, exec or LUA to go into the slowlog or to populate statistics. */
int update_command_stats = !isAOFLoadingContext();
/* We want to be aware of a client which is making a first time attempt to execute this command
* and a client which is reprocessing command again (after being unblocked).
* Blocked clients can be blocked in different places and not always it means the call() function has been
* called. For example this is required for avoiding double logging to monitors.*/
int reprocessing_command = (c->flags & CLIENT_REEXECUTING_COMMAND) ? 1 : 0;
/* Initialization: clear the flags that must be set by the command on
* demand, and initialize the array for additional commands propagation. */
c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP);
server.executing_client = c 是「当前正在执行的命令上下文」。server.current_client 是「当前连接」,两者不同 —— 嵌套调用(脚本里调命令)时,current_client 还是最外层那个客户端,executing_client 指向内层。
c->flags &= ~(CLIENT_FORCE_AOF|CLIENT_FORCE_REPL|CLIENT_PREVENT_PROP) 是清理上一条命令
留下的传播标记。这些标记是「一次性」的,用完就清。
update_command_stats = !isAOFLoadingContext():AOF 加载期间执行的命令
不进慢日志、不进统计。否则 AOF 重放会把 commandstats 冲得一塌糊涂。
8.4.2 脏计数快照
// src/server.c:4251-4254
/* Call the command. */
dirty = server.dirty;
long long old_master_repl_offset = server.master_repl_offset;
incrCommandStatsOnError(NULL, 0);
这就是 server.dirty 的全部秘密:命令执行前拍一张快照,
执行后再拍一张,差值就是「这条命令改了多少数据」。
// src/server.c:4352-4353
dirty = server.dirty-dirty;
if (dirty < 0) dirty = 0;
if (dirty < 0) dirty = 0; 是防一手 —— server.dirty 在某些路径下会被重置
(比如 BGSAVE 之后 src/server.c:3237 有 server.dirty = 0;),
差值可能变成负数,这时当成 0 处理。
server.dirty 是长整型(src/server.h:2506),因为它是「自上次保存以来的改动数」,
会一直涨到下次 RDB 保存为止。
8.4.3 执行本体
// src/server.c:4318-4330
int call_targets = getPropagateTargetsForCall(c, flags);
int prev_targets = server.allowed_propagate_targets;
server.allowed_propagate_targets = prev_targets & call_targets;
c->cmd->proc(c);
server.allowed_propagate_targets = prev_targets;
exitExecutionUnit();
/* In case client is blocked after trying to execute the command,
* it means the execution is not yet completed and we MIGHT reprocess the command in the future. */
if (!(c->flags & CLIENT_BLOCKED)) c->flags &= ~(CLIENT_EXECUTING_COMMAND);
c->cmd->proc(c) 就是全部。一行。所有命令的实现都是 void xxxCommand(client *c),
参数只有客户端指针 —— 值从 c->argv 里取,回复往 c->reply 里写。
前面那几行 allowed_propagate_targets 是传播权限的传递:call() 递归调用时,内外层的传播目标取交集。注释在 src/server.c:4310-4317
解释了一个具体场景:模块 A 调模块 B,B 内部调 INCR,最后 A 调RM_ReplicateVerbatim —— 副本应该只看到 A,不该看到那个 INCR。
exitExecutionUnit() 是离开执行单元(一个 Lua 脚本或一次 RM_Call 是一个执行单元),
用来做嵌套层级的收尾。
8.4.4 耗时统计
// src/server.c:4332-4342
/* In order to avoid performance implication due to querying the clock using a system call 3 times,
* we use a monotonic clock, when we are sure its cost is very low, and fall back to non-monotonic call otherwise. */
ustime_t duration;
if (use_hw_clock)
duration = getMonotonicUs() - monotonic_start;
else
duration = ustime() - call_timer;
c->duration += duration;
/* Store for afterCommandEx before we reset c->duration. */
ustime_t total_duration = c->duration;
用单调时钟(getMonotonicUs)而不是墙上时钟(ustime) —— 因为系统时间会被 NTP 调整,
往回跳会导致耗时变成负数。但单调时钟读一次也是系统调用,所以只在确认成本很低时用
(monotonicGetType() == MONOTONIC_CLOCK_HW,即 CLOCK_MONOTONIC_RAW 这类硬件时钟)。
c->duration += duration 是累加而不是赋值 —— 因为一条命令可能被多次 call():
比如 BLPOP 挂起、客户端被阻塞、之后被唤醒重新执行。这时候 c->duration 要算总耗时。
8.5 阶段四:Redis 记了哪些账
命令执行完,call() 记一串账。
8.5.1 延迟事件
// src/server.c:4376-4385
/* Record the latency this command induced on the main thread.
* unless instructed by the caller not to log. (happens when processing
* a MULTI-EXEC from inside an AOF). */
if (update_command_stats) {
char *latency_event = (real_cmd->flags & CMD_FAST) ?
"fast-command" : "command";
latencyAddSampleIfNeeded(latency_event,duration/1000);
if (server.execution_nesting == 0)
durationAddSample(EL_DURATION_TYPE_CMD, duration);
}
两个延迟事件名:fast-command(CMD_FAST)和 command。duration/1000 是毫秒。LATENCY DOCTOR 和 LATENCY HISTORY 看的就是这些。
server.execution_nesting == 0 才是最外层 —— 嵌套调用不重复记,
否则一条 EVAL 会在 command 事件上记两次。
8.5.2 慢日志
// src/server.c:4387-4396
/* Log the command into the Slow log if needed (also flags off-CPU time).
* If the client is blocked we will handle slowlog when it is unblocked. */
if (update_command_stats && !(c->flags & CLIENT_BLOCKED))
/* Measure only if c->duration is this run alone (a command re-executed
* after blocking also carries the time of its earlier run, which the
* window doesn't cover), and on a module thread only if it was sampled. */
slowlogPushCurrentCommand(c, real_cmd, c->duration,
c->duration == duration && server.off_cpu_tracking &&
((on_main_thread && cpu_tracked) || sample_cpu) ?
&window_start : NULL);
慢日志记的是 c->duration(累计耗时),不是 duration(本次耗时)。
而 CPU 采样窗口只在「本次就是全部」时才用 —— 因为被阻塞后重新执行的命令,
前一次的耗时不在这个窗口里。
8.5.3 MONITOR 与 commandstats
// src/server.c:4398-4418
/* Send the command to clients in MONITOR mode if applicable,
* since some administrative commands are considered too dangerous to be shown.
* Other exceptions is a client which is unblocked and retrying to process the command
* or we are currently in the process of loading AOF. */
if (update_command_stats && !reprocessing_command &&
!(c->cmd->flags & (CMD_SKIP_MONITOR|CMD_ADMIN)))
{
robj **argv = c->original_argv ? c->original_argv : c->argv;
int argc = c->original_argv ? c->original_argc : c->argc;
replicationFeedMonitors(c,server.monitors,c->db->id,argv,argc);
}
/* Populate the per-command and per-slot statistics that we show in INFO commandstats and CLUSTER SLOT-STATS,
* respectively. If the client is blocked we will handle latency stats and duration when it is unblocked. */
if (update_command_stats && !(c->flags & CLIENT_BLOCKED)) {
real_cmd->calls++;
real_cmd->microseconds += c->duration;
if (server.latency_tracking_enabled && !(c->flags & CLIENT_BLOCKED))
updateCommandLatencyHistogram(&(real_cmd->latency_histogram), c->duration*1000);
clusterSlotStatsAddCpuDuration(c, c->duration);
}
real_cmd->calls++ 和 real_cmd->microseconds += c->duration 就是INFO commandstats 的数据源。
注意 real_cmd 不一定是 c->cmd。注释在 src/server.c:4372-4374:
「c->cmd 和 c->lastcmd 可能不同,比如 MULTI-EXEC 或者被改写的命令
(EXPIRE、GEOADD 这些)」。c->realcmd 是用户实际敲的那条命令,c->cmd 是内部真正执行的那个。统计要按用户视角记,所以用 real_cmd。
c->original_argv 是用户原始的参数(有些命令会改写参数,比如SET k v EX 10 会被改写成 SET k v PX 10000)。MONITOR 和慢日志要显示原始的,
所以优先用 c->original_argv。
8.5.4 全局计数与收尾
// src/server.c:4500-4512
if (!(c->flags & CLIENT_BLOCKED)) {
/* Modules may call commands in cron, in which case server.current_client
* is not set. */
if (server.current_client) {
server.current_client->commands_processed++;
}
server.stat_numcommands++;
}
/* Do some maintenance job and cleanup.
* Use total_duration (not stack duration) so blocked-client reprocessing
* still credits accumulated time when pending UNKNOWN ops are drained. */
afterCommandEx(c, total_duration, ops_before);
server.stat_numcommands 就是 INFO 里那个 total_commands_processed。
afterCommandEx 做的是「命令执行完之后还要做的事」:
// src/server.c:4598-4626
static void afterCommandEx(client *c, long duration, int ops_before) {
/* Nested call (script / RM_Call): stamp only UNKNOWN ops this call
* queued so leftover does not land on an outer command's UNKNOWN.
* Skip when AOF is off: leftover is only consumed by feedAppendOnlyFile. */
if (server.aof_state != AOF_OFF &&
server.execution_nesting &&
server.also_propagate.numops > ops_before)
{
assignLeftoverDurationToUnknownOps(ops_before, duration);
}
/* Should be done before trackingHandlePendingKeyInvalidations so that we
* reply to client before invalidating cache (makes more sense) */
postExecutionUnitOperationsEx(duration);
/* Flush pending tracking invalidations. */
trackingHandlePendingKeyInvalidations();
clusterSlotStatsAddNetworkBytesOutForUserClient(c);
/* Flush other pending push messages. only when we are not in nested call.
* So the messages are not interleaved with transaction response. */
if (!server.execution_nesting)
listJoin(c->reply, server.pending_push_messages);
/* Run debug assertions if any are enabled */
if (unlikely(server.dbg_assert_flags))
dbgRunAssertions(c->db);
}
四项收尾:补齐未知时长的传播操作、结束执行单元、刷 tracking 失效消息、
合推送消息。
「先回客户端、再失效缓存」这个顺序是刻意的 —— 注释写明「这样更合理」。
8.6 阶段五:传播 —— 写命令怎么进复制流
// src/server.c:4444-4475
/* Propagate the command into the AOF and replication link.
* We never propagate EXEC explicitly, it will be implicitly
* propagated if needed (see propagatePendingCommands).
* Also, module commands take care of themselves */
if (flags & CMD_CALL_PROPAGATE &&
(c->flags & CLIENT_PREVENT_PROP) != CLIENT_PREVENT_PROP &&
c->cmd->proc != execCommand &&
!(c->cmd->flags & CMD_MODULE))
{
int propagate_flags = PROPAGATE_NONE;
/* Check if the command operated changes in the data set. If so
* set for replication / AOF propagation. */
if (dirty) propagate_flags |= (PROPAGATE_AOF|PROPAGATE_REPL);
/* If the client forced AOF / replication of the command, set
* the flags regardless of the command effects on the data set. */
if (c->flags & CLIENT_FORCE_REPL) propagate_flags |= PROPAGATE_REPL;
if (c->flags & CLIENT_FORCE_AOF) propagate_flags |= PROPAGATE_AOF;
/* However prevent AOF / replication propagation if the command
* implementation called preventCommandPropagation() or similar, or if
* this call() is not allowed to reach the target at all. */
if (c->flags & CLIENT_PREVENT_REPL_PROP) propagate_flags &= ~PROPAGATE_REPL;
if (c->flags & CLIENT_PREVENT_AOF_PROP) propagate_flags &= ~PROPAGATE_AOF;
propagate_flags &= call_targets;
/* Call alsoPropagate() only if at least one of AOF / replication
* propagation is needed. */
if (propagate_flags != PROPAGATE_NONE)
alsoPropagateEx(c->db->id,c->argv,c->argc,propagate_flags,duration);
}
四个要点:
dirty是「要不要传播」的默认判据。命令没改数据(GET)就不传播。CLIENT_FORCE_REPL/CLIENT_FORCE_AOF可以强制传播 ——SPOP这类命令需要:它实际改的是集合,但传播出去的是SREM,
主命令本身要传播,所以用forceCommandPropagation。CLIENT_PREVENT_REPL_PROP/CLIENT_PREVENT_AOF_PROP可以单独禁止
某一个目标。preventCommandReplication(c)只禁复制,不禁 AOF。EXEC不显式传播,模块命令(CMD_MODULE)自己管 —— 因为模块的传播
规则五花八门,Redis 不猜。
传播的具体动作在 alsoPropagateEx:
// src/server.c:3900-3918
void alsoPropagateEx(int dbid, robj **argv, int argc, int target, long long duration) {
robj **argvcopy;
int j;
/* Drop the targets the command currently running is not allowed to reach,
* so that its effect commands don't end up in an AOF / replica excluded by
* Lua redis.set_repl() or by a selective RM_Call(). */
target &= server.allowed_propagate_targets;
if (!shouldPropagate(target))
return;
argvcopy = zmalloc(sizeof(robj*)*argc);
for (j = 0; j < argc; j++) {
argvcopy[j] = argv[j];
incrRefCount(argv[j]);
}
redisOpArrayAppend(&server.also_propagate,dbid,argvcopy,argc,target,duration);
}
传播不是立刻做的,是排进 server.also_propagate 队列。
真正写进 AOF 和发给副本是后面的 propagateNow:
// src/server.c:3860-3887
static void propagateNow(int dbid, robj **argv, int argc, int target, long long duration) {
/* Every PROP_DURATION_UNKNOWN op must have been resolved by
* assignLeftoverDurationToUnknownOps() before reaching here. Letting the
* reserved value through would decrement server.aof_cmd_duration. */
debugServerAssert(duration != PROP_DURATION_UNKNOWN);
if (duration < 0) duration = 0;
/* No need to intersect 'target' with server.allowed_propagate_targets: it is
* already the final one, either decided when the op was queued by
* alsoPropagate() (or deliberately left unrestricted by
* alsoPropagateForced()), or the MULTI / EXEC wrapping the ops. Restricting
* it again by what the command running now may reach could only drop an op
* that was legitimately queued. */
if (!shouldPropagate(target))
return;
/* This needs to be unreachable since the dataset should be fixed during
* replica pause (otherwise data may be lost during a failover) */
serverAssert(!(isPausedActions(PAUSE_ACTION_REPLICA) &&
(!server.client_pause_in_transaction)));
if (server.aof_state != AOF_OFF && target & PROPAGATE_AOF)
feedAppendOnlyFile(dbid,argv,argc,duration);
if (target & PROPAGATE_REPL) {
replicationFeedSlaves(server.slaves,dbid,argv,argc);
asmFeedMigrationClient(argv, argc);
}
}
asmFeedMigrationClient 是这棵树的新东西 —— 原子槽位迁移(ASM)也需要收到
复制流,否则迁走的槽位数据就不一致了。
8.7 阶段六:过期键是在哪一步被删掉的
8.7.1 lookupKey —— 一个函数,两个身份
7.x 里 lookupKey 返回 robj *。这棵树返回 kvobj *:
// src/db.c:302-330
kvobj *lookupKey(redisDb *db, robj *key, int flags, dictEntryLink *link) {
kvobj *val = dbFindByLink(db, key->ptr, link);
if (val) {
/* Forcing deletion of expired keys on a replica makes the replica
* inconsistent with the master. We forbid it on readonly replicas, but
* we have to allow it on writable replicas to make write commands
* behave consistently.
*
* It's possible that the WRITE flag is set even during a readonly
* command, since the command may trigger events that cause modules to
* perform additional writes. */
int is_ro_replica = server.masterhost && server.repl_slave_ro;
int expire_flags = 0;
if (flags & LOOKUP_WRITE && !is_ro_replica)
expire_flags |= EXPIRE_FORCE_DELETE_EXPIRED;
if (flags & LOOKUP_NOEXPIRE)
expire_flags |= EXPIRE_AVOID_DELETE_EXPIRED;
if (flags & LOOKUP_ACCESS_EXPIRED)
expire_flags |= EXPIRE_ALLOW_ACCESS_EXPIRED;
if (flags & LOOKUP_ACCESS_TRIMMED)
expire_flags |= EXPIRE_ALLOW_ACCESS_TRIMMED;
if (expireIfNeeded(db, key, val, expire_flags) != KEY_VALID) {
/* The key is no longer valid. */
val = NULL;
if (link) *link = NULL;
}
}
expireIfNeeded 就嵌在 lookupKey 里。查一个 key,顺手检查它是不是过期了,
过期就当场删掉并返回 NULL。这就是「惰性过期」。
kvobj 是 robj 的一个特化版本:
// src/object.h:104-122
struct redisObject {
unsigned type:4;
unsigned encoding:5;
unsigned refcount : OBJ_REFCOUNT_BITS;
unsigned iskvobj : 1; /* 1 if this struct serves as a kvobj base */
/* metabits and lru are Relevant only when iskvobj is set: */
unsigned metabits :8; /* Bitmap of metadata (+expiry) attached to this kvobj */
unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
* LFU data (least significant 8 bits frequency
* and most significant 16 bits access time). */
void *ptr;
};
/* robj - General purpose redis object */
typedef struct redisObject robj;
/* kvobj: see header comment above for definition and memory layout. */
typedef struct redisObject kvobj;
kvobj 和 robj 是同一个结构体,靠 iskvobj 位区分。kvobj 多了两样东西:key 本身(嵌在结构体后面)和元数据位(metabits,装过期时间等)。
这样「key + value + TTL」打包成一个对象,字典里只需要存一个指针。
8.7.2 expireIfNeeded —— 它到底在哪个文件里
这是本篇最值得单独拎出来的一个事实:
expireIfNeeded 在 src/db.c,不在 src/expire.c。
7.x 里 expireIfNeeded 在 src/expire.c。这棵树把它挪到了 src/db.c:3135。src/expire.c 还在(984 行),但它管的是主动过期周期
(activeExpireCycle、activeSubexpires)和 EXPIRE/TTL 命令本身。
所以在这棵树里:
| 文件 | 管什么 |
|---|---|
src/db.c:3135 expireIfNeeded |
惰性过期 —— 查 key 时顺手判断 |
src/expire.c:40 activeExpireCycleTryExpire |
主动过期 —— 后台抽样扫描 |
src/expire.c:303 activeExpireCycle |
主动过期的调度入口 |
这个区分很重要:「key 什么时候真正被删掉」有两个时机 ——
访问它的时候(惰性),或者后台扫描的时候(主动)。
8.7.3 四个返回值
// src/db.c:42-48
/* Return values for expireIfNeeded */
typedef enum {
KEY_VALID = 0, /* Could be volatile and not yet expired, non-volatile, or even non-existing key. */
KEY_EXPIRED, /* Logically expired but not yet deleted. */
KEY_DELETED, /* The key was deleted now. */
KEY_TRIMMED /* Logically trimmed but not yet deleted. */
} keyStatus;
四个状态:
KEY_VALID:有效(或者压根不存在,或者有 TTL 但没到期)。KEY_EXPIRED:逻辑上过期了,但没删 —— 副本上就是这种情况。KEY_DELETED:刚才被删掉了。KEY_TRIMMED:逻辑上被裁剪了,但没删 —— 槽位迁移的新概念。
KEY_TRIMMED 是这棵树独有的。副本上不删过期 key:
// src/db.c:3174-3182
if (server.masterhost != NULL || server.cluster_enabled) {
if (server.current_client && (server.current_client->flags & CLIENT_MASTER)) return KEY_VALID;
if (server.masterhost != NULL && !(flags & EXPIRE_FORCE_DELETE_EXPIRED)) return KEY_EXPIRED;
}
/* Check if user configuration disables lazy-expire deletions in current state.
* This will only apply if the server doesn't mandate key deletion to operate correctly (write commands). */
if (!(flags & EXPIRE_FORCE_DELETE_EXPIRED) && !confAllowsExpireDel())
return KEY_EXPIRED;
副本上的过期 key 由主节点发 DEL 来删。副本自己删会跟主节点不一致。
所以副本只返回 KEY_EXPIRED(告诉调用方「逻辑上它没了」),不真删。
例外是可写副本:LOOKUP_WRITE 且不是只读副本时,
带 EXPIRE_FORCE_DELETE_EXPIRED,会真删。因为写命令在可写副本上要有确定的行为。
8.7.4 查 key 的四个包装
// src/db.c:372-395
kvobj *lookupKeyReadWithFlags(redisDb *db, robj *key, int flags) {
serverAssert(!(flags & LOOKUP_WRITE));
return lookupKey(db, key, flags, NULL);
}
/* Like lookupKeyReadWithFlags(), but does not use any flag, which is the
* common case. */
kvobj *lookupKeyRead(redisDb *db, robj *key) {
return lookupKeyReadWithFlags(db,key,LOOKUP_NONE);
}
/* Lookup a key for write operations, and as a side effect, if needed, expires
* the key if its TTL is reached. It's equivalent to lookupKey() with the
* LOOKUP_WRITE flag added.
*
* Returns the linked value object if the key exists or NULL if the key
* does not exist in the specified DB. */
kvobj *lookupKeyWriteWithFlags(redisDb *db, robj *key, int flags) {
return lookupKey(db, key, flags | LOOKUP_WRITE, NULL);
}
kvobj *lookupKeyWrite(redisDb *db, robj *key) {
return lookupKeyWriteWithFlags(db, key, LOOKUP_NONE);
}
「读」和「写」的区别只有一个 flag:LOOKUP_WRITE。
读路径不会真删过期 key(EXPIRE_FORCE_DELETE_EXPIRED 不设),
写路径会。
命令实现里最常见的是这两个「OrReply」包装:
// src/db.c:408-418
kvobj *lookupKeyReadOrReply(client *c, robj *key, robj *reply) {
kvobj *kv = lookupKeyRead(c->db, key);
if (!kv) addReplyOrErrorObject(c, reply);
return kv;
}
kvobj *lookupKeyWriteOrReply(client *c, robj *key, robj *reply) {
kvobj *kv = lookupKeyWrite(c->db, key);
if (!kv) addReplyOrErrorObject(c, reply);
return kv;
}
查不到就直接把「空回复」写出去(shared.null[c->resp]),返回 NULL 让命令自己处理。
8.7.5 一个完整的例子:GET
// src/t_string.c:456-468
int getGenericCommand(client *c) {
kvobj *o;
if ((o = lookupKeyReadOrReply(c, c->argv[1], shared.null[c->resp])) == NULL)
return C_OK;
if (checkType(c,o,OBJ_STRING)) {
return C_ERR;
}
addReplyBulk(c,o);
return C_OK;
}
四行干四件事:查 key(顺带处理过期)→ 查类型 → 回 bulk 字符串。
注意 shared.null[c->resp] —— RESP2 回 $-1,RESP3 回 _(src/server.c:2323-2324)。
同一个命令,不同协议版本回不同的空值标记。
8.8 阶段七:回复怎么写回去
// src/networking.c:649-664
void addReply(client *c, robj *obj) {
if (_prepareClientToWrite(c) != C_OK) return;
if (sdsEncodedObject(obj)) {
_addReplyToBufferOrList(c,obj->ptr,sdslen(obj->ptr));
} else if (obj->encoding == OBJ_ENCODING_INT) {
/* For integer encoded strings we just convert it into a string
* using our optimized function, and attach the resulting string
* to the output buffer. */
char buf[32];
size_t len = ll2string(buf,sizeof(buf),(long)obj->ptr);
_addReplyToBufferOrList(c,buf,len);
} else {
serverPanic("Wrong obj->encoding in addReply()");
}
}
回复不进 socket,进的是客户端的输出缓冲(c->buf 或 c->reply 链表)。
什么时候真正写回 socket 由事件循环决定(第 10 章)。
bulk 字符串走另一条:
// src/networking.c:1387-1410
void addReplyBulkWithFlag(client *c, robj *obj, int avoid_copy) {
if (_prepareClientToWrite(c) != C_OK) return;
if (sdsEncodedObject(obj)) {
const size_t len = sdslen(obj->ptr);
if (avoid_copy && tryAvoidBulkStrCopyToReply(c, obj, len) == C_OK)
return;
_addReplyLongLongBulk(c, len);
_addReplyToBufferOrList(c,obj->ptr,len);
_addReplyToBufferOrList(c,"\r\n",2);
} else if (obj->encoding == OBJ_ENCODING_INT) {
/* For integer encoded strings we just convert it into a string
* using our optimized function, and attach the resulting string
* to the output buffer. */
char buf[34];
size_t len = ll2string(buf,sizeof(buf),(long)obj->ptr);
buf[len] = '\r';
buf[len+1] = '\n';
_addReplyLongLongBulk(c, len);
_addReplyToBufferOrList(c,buf,len+2);
} else {
serverPanic("Wrong obj->encoding in addReply()");
}
}
tryAvoidBulkStrCopyToReply 是「零拷贝」优化:如果客户端的输出缓冲尾部正好
是个能就地扩展的 sds,就把对象的字符串挂上去而不是复制一份。
大 value 的场景省一次 memcpy。
写完之后是收尾:
// src/networking.c:3708-3732
int processCommandAndResetClient(client *c) {
int deadclient = 0;
client *old_client = server.current_client;
server.current_client = c;
if (processCommand(c) == C_OK) {
commandProcessed(c);
/* Update the client's memory to include output buffer growth following the
* processed command. */
if (c->conn) updateClientMemUsageAndBucket(c);
}
if (server.current_client == NULL) deadclient = 1;
/*
* Restore the old client, this is needed because when a script
* times out, we will get into this code from processEventsWhileBlocked.
* Which will cause to set the server.current_client. If not restored
* we will return 1 to our caller which will falsely indicate the client
* is dead and will stop reading from its buffer.
*/
server.current_client = old_client;
/* performEvictions may flush slave output buffers. This may
* result in a slave, that may be the active client, to be
* freed. */
return deadclient ? C_ERR : C_OK;
}
server.current_client = old_client 这个恢复动作很有意思,注释解释了原因:
脚本超时的时候,processEventsWhileBlocked 也会走这条路径,
如果这里不恢复,current_client 会被污染,外层以为客户端死了。
commandProcessed 接着处理复制偏移:
// src/networking.c:3662-3698
void commandProcessed(client *c) {
/* If client is blocked(including paused), just return avoid reset and replicate.
*
* 1. Don't reset the client structure for blocked clients, so that the reply
* callback will still be able to access the client argv and argc fields.
* The client will be reset in unblockClient().
* 2. Don't update replication offset or propagate commands to replicas,
* since we have not applied the command. */
if (c->flags & CLIENT_BLOCKED) return;
prepareForNextCommand(c, 1);
long long prev_offset = c->reploff;
if (c->flags & CLIENT_MASTER && !(c->flags & CLIENT_MULTI)) {
/* Update the applied replication offset of our master. */
serverAssert(c->reploff_next > 0);
c->reploff = c->reploff_next;
}
/* If the client is a master we need to compute the difference
* between the applied offset before and after processing the buffer,
* to understand how much of the replication stream was actually
* applied to the master state: this quantity, and its corresponding
* part of the replication stream, will be propagated to the
* sub-replicas and to the replication backlog. */
if (c->flags & CLIENT_MASTER) {
long long applied = c->reploff - prev_offset;
if (applied) {
replicationFeedStreamFromMasterStream(c->querybuf+c->repl_applied,applied);
c->repl_applied += applied;
/* Update the atomic slot migration task's applied bytes. */
if (c->flags & CLIENT_ASM_IMPORTING)
asmImportIncrAppliedBytes(c->task, applied);
}
}
}
「级联复制」的关键:副本作为主节点的客户端,主节点发来的字节流原样转发给下级副本
(replicationFeedStreamFromMasterStream)。这就是为什么 Redis 的复制是
「一主多从,副本之间也能串起来」而不用每个副本都连主节点。
8.9 与网文 / 7.x 的差异
| 事项 | 网文 / 7.x | 这棵树 | 出处 |
|---|---|---|---|
| 命令查找时机 | 在 processCommand 里 |
在解析阶段 preprocessCommand 里 |
src/server.c:4705 |
| 命令容器 | c->argv / c->argc 直接躺在客户端上 |
独立的 pendingCommand 结构 + 队列 |
src/server.h:2945 |
| 解析阶段就能报错 | 不能 | 能:CLIENT_READ_COMMAND_NOT_FOUND / CLIENT_READ_BAD_ARITY |
src/server.h:528-529 |
| 命令复用 | 只复用 c->lastcmd |
复用倒数第二条 pendingCommand |
src/server.c:4719 |
lookupKey 返回 |
robj * |
kvobj * |
src/db.c:302 |
expireIfNeeded 位置 |
src/expire.c |
src/db.c:3135 |
src/db.c:3135 |
| 过期状态 | int(0/1) |
枚举 KEY_VALID/EXPIRED/DELETED/TRIMMED |
src/db.c:42-48 |
| 槽位迁移中的 key | 无此概念 | 新增 KEY_TRIMMED 状态 |
src/db.c:47 |
| 脚本属性 | redis.set_repl() 运行时设置 |
声明式,脚本自己声明读写属性 | src/server.c:4685-4697 |
| 事务属性 | 逐条命令检查 | 事务内 flag 取并集,整包取最严 | src/multi.c:62-63 |
| 复制流喂给谁 | 只喂副本 | 副本 + 槽位迁移客户端 | src/server.c:3885 |
| 命令级耗时 | c->duration |
累加 + total_duration 分离 |
src/server.c:4340-4342 |
| 统计记在 | c->cmd |
c->realcmd(用户视角) |
src/server.c:4413 |
| 热点统计 | 无 | hotkeyStats* 系列 |
src/server.c:4431、src/server.c:4521 |
| 槽位级统计 | 无 | clusterSlotStatsAdd* |
src/server.c:4417 |
| 命令失败统计 | 有 | 区分模块内部消化的错误 | src/server.c:4356-4364 |
最容易踩坑的三条:
- 命令在解析阶段就查好了。你在
processCommand里看到的c->cmd可能
是几毫秒前在 IO 线程里查的。模块的 CommandFilters 改完命令后,processCommand会重新查一次(src/server.c:4798-4805)。 expireIfNeeded搬了家。按 7.x 的记忆去src/expire.c找会扑空。- 返回的是
kvobj *不是robj *。kvobj多了 key 和元数据位,
用robj *接会丢信息。
8.10 本章要点回顾
关键要点
- 命令查找被提到了解析阶段:
preprocessCommand(src/server.c:4705)在 IO 线程里就把命令、key、槽位算好,processCommand直接取c->lookedcmd。 - 一条命令的容器是
pendingCommand(src/server.h:2945),是双向链表节点 —— 队尾可能被复用接着解析,队头等着被执行。 - 解析阶段就能报错:
CLIENT_READ_COMMAND_NOT_FOUND(14)和CLIENT_READ_BAD_ARITY(15)(src/server.h:528-529),命令不存在和参数个数不对在解析时就被抓住。 - 命令复用是双份的:
isCommandReusable(src/server.c:111)在解析阶段复用倒数第二条命令的查表结果;管道里连续 1000 条GET只查一次表。但带子命令的命令不参与复用。 processCommand有 385 行,绝大部分是关卡(src/server.c:4761-5145):从认证、ACL、集群重定向到 OOM、只读副本、加载中、忙、客户端暂停,一共二十一道。- 关卡顺序有讲究:认证在 ACL 之前;命令存在性在认证之前(未登录也要能看出命令拼没拼错);内部命令对非内部连接直接隐形(
src/server.c:4817)。 - 「默认拒绝」是这棵树的安全基调:
is_denystale_command = !(cmd_flags & CMD_STALE)、is_denyloading_command = !(cmd_flags & CMD_LOADING)—— 默认拦,显式开洞。 - 事务属性取并集:
c->mstate.cmd_flags |= cmd_flags(src/multi.c:62)—— 队列里只要有一条是写的,整个事务就是写的;只要有一条禁 OOM,整个事务就禁。 - 脚本的属性是声明式的:
getCommandFlags(src/server.c:4685)会用evalGetCommandFlags/fcallGetCommandFlags覆盖命令表的静态 flag。 server.dirty决定要不要传播:执行前拍快照、执行后算差值,差值非零才进 AOF 和复制流(src/server.c:4252、4352、4457)。- 传播是排队的不是立刻做的:
alsoPropagateEx挂进server.also_propagate,真正的feedAppendOnlyFile/replicationFeedSlaves在后面的propagateNow里(src/server.c:3860)。 - 传播目标可以精细到 AOF 和复制分开控制:
CLIENT_FORCE_REPL/CLIENT_FORCE_AOF强制,CLIENT_PREVENT_REPL_PROP/CLIENT_PREVENT_AOF_PROP单独禁。 - 过期键是查的时候顺手删的:
expireIfNeeded嵌在lookupKey里(src/db.c:325),这是惰性过期;后台还有主动过期周期(src/expire.c:303)。 expireIfNeeded在src/db.c:3135,不在src/expire.c—— 这是这棵树相对 7.x 的搬家。- 副本不删过期 key:只返回
KEY_EXPIRED(逻辑上没了),真删交给主节点发DEL(src/db.c:3174-3177);可写副本是例外。 - 统计记在
c->realcmd上而不是c->cmd—— 用户视角 vs 内部视角(src/server.c:4413)。 lookupKey返回kvobj *:kvobj和robj是同一个结构体,靠iskvobj位区分,kvobj多带 key 和metabits(src/object.h:104)。- 级联复制靠
replicationFeedStreamFromMasterStream:副本把从主节点收到的字节流原样转发给下级(src/networking.c:3690)。
8.11 接下来
本文把命令从被找到到执行完记账这条链走完了。但还有三个问题没答:
- 过期和淘汰这两个后台机制怎么配合?惰性过期在访问时删,主动过期在后台扫,
两者同时存在会不会重复删?KEY_EXPIRED和KEY_DELETED的区分在这里才显出意义
—— 那是第 06 章《紧凑编码与编码转换》和第 12 章《复制链路》要接上的线。 - 数据怎么落盘?
server.dirty决定进不进 AOF,但 AOF 文件长什么样、
RDB 怎么生成、dirty什么时候归零 —— 那是第 11 章《RDB 与 AOF》。 - 复制流的具体格式?
replicationFeedSlaves怎么把命令编码成字节、
副本怎么应用 —— 那是第 12 章。
另外提醒一句读法上的事:本文的 8.3.1 那张关卡表是排查线上问题的索引。
下次客户端收到一个你不熟悉的错误串,先回到那张表上定位是第几道关卡,
再跳到对应的源码行 —— 比从头读代码快得多。
引用
本文涉及的结构体、宏与函数,均取自 Redis 源码
(/work/ai/cwork/redis,分支 unstable,git describe --tags = 8.12-m02-int-184-gff28c55fc,HEAD = ff28c55f,
核对时间:2026-12-04):
| 事实 | 出处 |
|---|---|
processCommand 全函数(385 行,21 道关卡) |
src/server.c:4761-5145 |
call() 函数定义 |
src/server.c:4223 |
afterCommandEx 的四项收尾 |
src/server.c:4598-4626 |
rejectCommand / rejectCommandSds / rejectCommandFormat |
src/server.c:4557-4591 |
commandCheckExistence(区分未知命令与未知子命令) |
src/server.c:4630-4666 |
commandCheckArity(arity 正负语义) |
src/server.c:4670-4680 |
getCommandFlags(脚本/函数属性覆盖静态 flag) |
src/server.c:4685-4697 |
preprocessCommand(解析阶段查命令、抽 key、算槽位) |
src/server.c:4705 |
isCommandReusable(命令复用判定) |
src/server.c:111-118 |
mustObeyClient(AOF 客户端与主节点客户端) |
src/server.c:3815-3817 |
processCommand 的执行/快照开头 |
src/server.c:4761-4780 |
processCommand 的命令查找与存在性/arity 检查 |
src/server.c:4794-4830 |
| 内部命令对非内部连接隐形 | src/server.c:4815-4819 |
CMD_PROTECTED 检查(DEBUG / MODULE) |
src/server.c:4834-4846 |
| 运行时 flag 求值(is_read / is_write / is_denyoom 等) | src/server.c:4849-4866 |
| 认证、事务内禁用、ACL 三道关卡 | src/server.c:4867-4892 |
| 集群重定向关卡(EXEC 与普通命令的不同处理) | src/server.c:4897-4918 |
evictClients 与 maxmemory / OOM 关卡 |
src/server.c:4934-4973 |
| 磁盘错误关卡 | src/server.c:4982-5007 |
| 副本数不足与只读副本关卡 | src/server.c:5009-5024 |
| 槽位迁移中阻塞主节点 | src/server.c:5032-5044 |
| Pub/Sub 上下文(RESP2 限制)关卡 | src/server.c:5046-5063 |
| 主链路断开、加载中、异步加载关卡 | src/server.c:5065-5087 |
| 忙(脚本 / 模块)关卡 | src/server.c:5089-5107 |
| 副本不许碰键空间、客户端暂停关卡 | src/server.c:5109-5125 |
事务排队与 call() 分岔 |
src/server.c:5127-5145 |
queueMultiCommand(事务 flag 并集与反集) |
src/multi.c:35-75 |
flagTransaction / execCommandAbort |
src/multi.c:86-89、src/multi.c:115-125 |
call() 的执行上下文与 flag 清理 |
src/server.c:4223-4242 |
server.dirty 快照 |
src/server.c:4251-4254 |
c->cmd->proc(c) 与传播目标传递 |
src/server.c:4318-4330 |
exitExecutionUnit |
src/server.c:4326 |
单调时钟耗时统计与 total_duration |
src/server.c:4332-4342 |
server.dirty 差值计算 |
src/server.c:4352-4353 |
| 模块内部消化错误时的失败计数 | src/server.c:4356-4364 |
延迟事件(command / fast-command) |
src/server.c:4376-4385 |
| 慢日志入队(累计耗时与 CPU 采样窗口) | src/server.c:4387-4396 |
| MONITOR 投喂与 commandstats 计数 | src/server.c:4398-4418 |
| 热点统计的当前命令准备与更新 | src/server.c:4427-4436 |
| 传播判定(dirty / FORCE / PREVENT / call_targets) | src/server.c:4444-4475 |
server.stat_numcommands 与 afterCommandEx 调用 |
src/server.c:4500-4512 |
| 热点统计收尾 | src/server.c:4517-4528 |
alsoPropagateEx(传播进队列) |
src/server.c:3900-3918 |
propagateNow(真正写 AOF 与喂副本) |
src/server.c:3860-3887 |
forceCommandPropagation / preventCommandPropagation 系列 |
src/server.c:3939-3959 |
getPropagateTargetsForCall |
src/server.c:3973-3980 |
slowlogPushCurrentCommand |
src/server.c:3984 |
shared.queued(+QUEUED) |
src/server.c:2276 |
共享错误串(-LOADING / -BUSY / -MASTERDOWN / -READONLY / -NOAUTH / -OOM / -EXECABORT / -NOREPLICAS) |
src/server.c:2295-2318 |
shared.null[2](RESP2 空值 $-1)与 shared.null[3](RESP3 空值 _) |
src/server.c:2323-2324 |
CMD_CALL_* 与 PROPAGATE_* 常量 |
src/server.h:784-794 |
processInputBuffer 的 lookahead 限制 |
src/networking.c:3862-3867 |
| 解析循环(pendingCommand 的申请、复用、预处理) | src/networking.c:3896-3946 |
消费队头命令并搬到 c->argv、预取命令 |
src/networking.c:3957-3984 |
processCommandAndResetClient(含 current_client 恢复) |
src/networking.c:3708-3732 |
commandProcessed(复制偏移与级联复制) |
src/networking.c:3662-3698 |
prepareForNextCommand |
src/networking.c:3648-3655 |
addReply(输出缓冲) |
src/networking.c:649-664 |
addReplyBulkWithFlag(零拷贝 bulk 回复) |
src/networking.c:1387-1409 |
struct pendingCommand 全文 |
src/server.h:2945-2961 |
CLIENT_READ_COMMAND_NOT_FOUND / CLIENT_READ_BAD_ARITY |
src/server.h:528-529 |
CLIENT_IO_PENDING_COMMAND 与 c->running_tid |
src/server.h:507、src/server.h:1585 |
struct redisObject 与 kvobj 别名 |
src/object.h:104-122 |
lookupKey(内嵌 expireIfNeeded) |
src/db.c:302-330 |
lookupKeyReadWithFlags / lookupKeyRead / lookupKeyWriteWithFlags / lookupKeyWrite |
src/db.c:372-395 |
lookupKeyReadOrReply / lookupKeyWriteOrReply |
src/db.c:408-418 |
dbFindByLink(新 dict 的 link 语义) |
src/db.c:3261-3274 |
keyStatus 枚举(VALID / EXPIRED / DELETED / TRIMMED) |
src/db.c:42-48 |
expireIfNeeded 的 flags 定义 |
src/db.c:36-40 |
expireIfNeeded 全文(含副本不删过期键的逻辑) |
src/db.c:3135-3200 |
getGenericCommand(GET 的实现) |
src/t_string.c:456-468 |
checkGoodReplicasStatus |
src/replication.c:4887-4892 |
evalGetCommandFlags(脚本声明属性) |
src/eval.c:404 |
fcallGetCommandFlags(函数声明属性) |
src/functions.c:609 |
hotkeyStatsPreCurrentCmd |
src/hotkeys.c:79 |
| 主动过期周期(与惰性过期相对) | src/expire.c:303 |