07 命令表:480 个 JSON 怎么变成命令


 TL;DR
Redis 的命令元数据不再是手写 C 数组,而是 480 个 JSON 生成出的 commands.def;本文讲清生成链路、命令表结构、字典查找与子命令、flag 与 ACL 类别、key_specs 的表达力。
难度 中等

引言:

  1. 读完这篇你能回答:Redis 的命令元数据现在是从哪来的? 为什么不是一份手写的 C 数组?
  2. src/commands/*.json 里那个 JSON 文件,是谁、什么时候、用什么脚本变成 C 代码的?
  3. 生成的 src/commands.def 有 13834 行,它凭什么能变成一张可以 O(1) 查的命令表?
  4. struct redisCommand 有二十多个字段,每一个分别管什么?哪些是声明期的、哪些是运行期才填的?
  5. OBJECT ENCODING 这种带子命令的命令,在表里是怎么存的?查的时候走几步?
  6. 一条命令的 flags(CMD_WRITE、CMD_DENYOOM……)和它的 ACL 类别(@read、@admin……)是两套东西吗?谁决定一个用户能不能调它?
  7. key_specs 里的 begin_search / find_keys 怎么描述「这条命令会碰哪些 key」?跟老式的 firstkey/lastkey/keystep 什么关系?

本文不讨论:命令被找到之后怎么被执行、怎么被检查、怎么被拒绝 —— 那是同赛道第 08 章
《一次命令的完整生命周期》的主题;也不讨论 Lua 与模块命令的注册路径(那是第 15 章)。
本文只讲一件事:命令这张表,是怎么造出来、怎么被查到的。

本文所有行号基于 /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 当版本。

7.1 命令表要解决什么问题

这一节回答:为什么 Redis 需要一张「命令表」,而不是直接 strcmp?

最朴素的实现是:在 switch (cmd[0]) 里比一遍字符串。480 条命令写下来,又长又慢,
而且每加一条命令都要动 C 代码 —— 加命令本来应该是「加一个 JSON 文件」的活。

Redis 需要的是一张表,满足三件事:

  1. 命令名 → 实现函数:给定 GET,要能拿到 getCommand 这个函数指针。
  2. 命令名 → 元数据:给定 GET,要能知道它是不是只读、会不会涨内存、需要几个参数、
    能碰几个 key、属于哪些 ACL 类别。这些元数据不是给 Redis 自己看的 —— 是给
    COMMAND INFO、COMMAND DOCS、ACL SETUSER、客户端库、代理用的。
  3. 查得快:每条命令都要查一次,这条路径在热路径上。

第三条决定了实现方式。7.x 的做法是把命令表做成一个按名字排序的静态数组,用二分查找。
这棵树换了做法:命令表是一个 dict(哈希表)。下面逐层看。

7.2 src/commands/*.json —— 元数据的源头

这一节回答:一个命令的元数据,长什么样?

命令元数据是这个仓库里唯一「以数据形式存在」的部分:src/commands/ 下 480 个 JSON 文件,
一个命令一个文件。目录里的 README 把话说得很清楚(src/commands/README.md:1-9):

// src/commands/README.md:1-9
This directory contains JSON files, one for each of Redis commands.

Each JSON contains all the information about the command itself, but these JSON files are not to be used directly!
Any third party who needs access to command information must get it from `COMMAND INFO` and `COMMAND DOCS`.
The output can be extracted in a JSON format by using `redis-cli --json`, in the same manner as in `utils/generate-commands-json.py`.

The JSON files are used to generate commands.def (and https://github.com/redis/docs/blob/main/data/commands.json) in Redis, and
despite looking similar to the output of `COMMAND` there are some fields and flags that are implicitly populated, and that's the
reason one shouldn't rely on the raw files.

注意最后一句:有些字段和 flag 是「隐式」补上的 —— 也就是说,JSON 里没有的东西,
不代表命令表里没有。这是后面 7.6 节要讲的关键。

以 GET 为例(src/commands/get.json:1-56):

// src/commands/get.json:1-35
{
    "GET": {
        "summary": "Returns the string value of a key.",
        "complexity": "O(1)",
        "group": "string",
        "since": "1.0.0",
        "arity": 2,
        "function": "getCommand",
        "command_flags": [
            "READONLY",
            "FAST"
        ],
        "acl_categories": [
            "STRING"
        ],
        "key_specs": [
            {
                "flags": [
                    "RO",
                    "ACCESS"
                ],
                "begin_search": {
                    "index": {
                        "pos": 1
                    }
                },
                "find_keys": {
                    "range": {
                        "lastkey": 0,
                        "step": 1,
                        "limit": 0
                    }
                }
            }
        ],

字段逐个说明:

字段 含义 GET 的值
summary 一句话说明,COMMAND DOCS 会返回 Returns the string value of a key.
complexity 复杂度描述,同上 O(1)
group 命令组,决定 COMMAND INFO 里的分组 string
since 首次出现的版本 1.0.0
arity 参数个数;正数是恰好几个,负数是「至少几个」 2(恰好 2 个)
function 实现函数的 C 名字 getCommand
command_flags 命令 flag,生成时变成 CMD_* 位 READONLY、FAST
acl_categories 显式声明的 ACL 类别 STRING
key_specs 这条命令会碰哪些 key 见 7.7 节
reply_schema 回复的 JSON Schema(尚未对外暴露) string 或 null

reply_schema 在 GET 里长这样(src/commands/get.json:36-47):

// src/commands/get.json:36-47
        "reply_schema": {
            "oneOf": [
                {
                    "description": "The value of the key.",
                    "type": "string"
                },
                {
                    "description": "Key does not exist.",
                    "type": "null"
                }
            ]
        },

目录 README 里对它有一句注解(src/commands/README.md:13-14):

// src/commands/README.md:13-14
The `reply_schema` section is a standard JSON Schema (see https://json-schema.org/) that describes the reply of each command.
It is designed to someday be used to auto-generate code in client libraries, but is not yet mature and is not exposed externally.

「尚未对外暴露」 是关键:这块只在编译期开 LOG_REQ_RES 时才进二进制(见 7.3 节)。

子命令的 JSON 是分文件的

带子命令的命令,container 那个 JSON 文件里只有父命令的壳。例如 OBJECT
(src/commands/object.json:1-9):

// src/commands/object.json:1-9
{
    "OBJECT": {
        "summary": "A container for object introspection commands.",
        "complexity": "Depends on subcommand.",
        "group": "generic",
        "since": "2.2.3",
        "arity": -2
    }
}

子命令另开文件,文件名是 父命令-子命令.json,并用 container 字段指回父命令。
例如 OBJECT ENCODING(src/commands/object-encoding.json:1-18):

// src/commands/object-encoding.json:1-18
{
    "ENCODING": {
        "summary": "Returns the internal encoding of a Redis object.",
        "complexity": "O(1)",
        "group": "generic",
        "since": "2.2.3",
        "arity": 3,
        "container": "OBJECT",
        "function": "objectCommand",
        "command_flags": [
            "READONLY"
        ],
        "acl_categories": [
            "KEYSPACE"
        ],
        "command_tips": [
            "NONDETERMINISTIC_OUTPUT"
        ],

注意 function 是 objectCommand 而不是 objectEncodingCommand —— 一个 C 函数处理多个子命令,
靠 argv[1] 分派。arity 是 3(OBJECT、ENCODING、key 三个参数)。

7.3 JSON → src/commands.def —— 代码生成

这一节回答:谁把这个 JSON 变成 C 代码?

不是 make 里的一行 sed,是一个 Python 脚本:utils/generate-command-code.py(635 行)。

生成规则写在 src/Makefile:512-522:

// src/Makefile:512-522
# The following files are checked in and don't normally need to be rebuilt. They
# are built only if python is available and their prereqs are modified.
ifneq (,$(PYTHON))
$(COMMANDS_DEF_FILENAME).def: commands/*.json ../utils/generate-command-code.py
  $(QUIET_GEN)$(PYTHON) ../utils/generate-command-code.py $(GEN_COMMANDS_FLAGS)

fmtargs.h: ../utils/generate-fmtargs.py
  $(QUITE_GEN)sed '/Everything below this line/,$$d' $@ > $@.tmp
  $(QUITE_GEN)$(PYTHON) ../utils/generate-fmtargs.py >> $@.tmp
  $(QUITE_GEN)mv $@.tmp $@
endif

看第一行注释就明白了:commands.def 是签进仓库的,只有当 JSON 或生成脚本变了才会重生成。
没有 Python 也能编译 —— 用仓库里那份已生成的。

COMMANDS_DEF_FILENAME 有两个取值,由是否定义 LOG_REQ_RES 决定(src/Makefile:406-412):

// src/Makefile:406-412
ifneq (, $(findstring LOG_REQ_RES, $(REDIS_CFLAGS)))
  COMMANDS_DEF_FILENAME=commands_with_reply_schema
  GEN_COMMANDS_FLAGS=--with-reply-schema
else
  COMMANDS_DEF_FILENAME=commands
  GEN_COMMANDS_FLAGS=
endif

也就是开 LOG_REQ_RES 会多生成一份带回复 schema 的表,普通构建走 commands.def。

生成的 commands.def 一共 13834 行,开头是这样的(src/commands.def:1-36):

// src/commands.def:1-36
/* Automatically generated by generate-command-code.py, do not edit. */


/* We have fabulous commands from
 * the fantastic
 * Redis Command Table! */

/* Must match redisCommandGroup */
const char *COMMAND_GROUP_STR[] = {
    "generic",
    "string",
    "list",
    "set",
    "sorted-set",
    "hash",
    "pubsub",
    "transactions",
    "connection",
    "server",
    "scripting",
    "hyperloglog",
    "cluster",
    "sentinel",
    "geo",
    "stream",
    "bitmap",
    "array",
    "module",
#ifdef ENABLE_GCRA
    "rate_limit"
#endif
};

const char *commandGroupStr(int index) {
    return COMMAND_GROUP_STR[index];
}

第一行就写着 do not edit —— 这是机器产物,人不该手改。

命令在 commands.def 里长什么样

GET 的条目在 src/commands.def:13806:

// src/commands.def:13806-13806
{MAKE_CMD("get","Returns the string value of a key.","O(1)","1.0.0",CMD_DOC_NONE,NULL,NULL,"string",COMMAND_GROUP_STRING,GET_History,0,GET_Tips,0,getCommand,2,CMD_READONLY|CMD_FAST,ACL_CATEGORY_STRING,GET_Keyspecs,1,NULL,1),.args=GET_Args},

这一行是 22 个位置参数,全部平铺。MAKE_CMD 是个宏,把位置参数转成结构体字段。
宏定义在 src/commands.c:4:

// src/commands.c:4-4
#define MAKE_CMD(name,summary,complexity,since,doc_flags,replaced,deprecated,group,group_enum,history,num_history,tips,num_tips,function,arity,flags,acl,key_specs,key_specs_num,get_keys,numargs) name,summary,complexity,since,doc_flags,replaced,deprecated,group_enum,history,num_history,tips,num_tips,function,arity,flags,acl,key_specs,key_specs_num,get_keys,numargs

注意宏里没有 group 这个参数名 —— 第 8 个位置参数 group(字符串 "string")被丢掉了,
只保留 group_enum(COMMAND_GROUP_STRING)。因为运行期只需要那个枚举,字符串版本由
COMMAND_GROUP_STR[] 反查。

src/commands.c 全文只有 13 行,就是几个宏加一个 include(src/commands.c:1-13):

// src/commands.c:1-13
#include "commands.h"
#include "server.h"

#define MAKE_CMD(name,summary,complexity,since,doc_flags,replaced,deprecated,group,group_enum,history,num_history,tips,num_tips,function,arity,flags,acl,key_specs,key_specs_num,get_keys,numargs) name,summary,complexity,since,doc_flags,replaced,deprecated,group_enum,history,num_history,tips,num_tips,function,arity,flags,acl,key_specs,key_specs_num,get_keys,numargs
#define MAKE_ARG(name,type,key_spec_index,token,summary,since,flags,numsubargs,deprecated_since) name,type,key_spec_index,token,summary,since,flags,deprecated_since,numsubargs
#define COMMAND_STRUCT redisCommand
#define COMMAND_ARG redisCommandArg

#ifdef LOG_REQ_RES
#include "commands_with_reply_schema.def"
#else
#include "commands.def"
#endif

整个 src/commands.c 就是一个 #include。这就是「JSON 化」的最终形态:
命令表完全由生成物决定,commands.c 只是把它编成结构体数组。

为什么要走 JSON 这条路

对比 7.x:那时候命令表是手写的 src/commands.c,一个巨大的 struct redisCommand redisCommandTable[],
每加一条命令就手写一个结构体初始化。痛点是:

  • 文档(summary、complexity、since)和代码写在同一个文件里,加命令要改两处;
  • 客户端库要拿命令元数据,只能去解析 Redis 的 C 源码;
  • 命令变多之后这个文件成了几千行,没人敢动。

JSON 化之后:命令的声明是数据,生成是机械的,文档和代码由同一份数据派生。
Redis 官方文档站的 commands.json 也是从这批 JSON 生成的(src/commands/README.md:7)。

7.4 命令表的运行时结构

这一节回答:生成的代码,在运行时长什么样?

struct redisCommand

定义在 src/server.h:3209-3261。这个结构体分两半:声明期数据(/* Declarative data */)
和运行期数据(/* Runtime populated data */)。

声明期部分(src/server.h:3209-3242):

// src/server.h:3209-3237
struct redisCommand {
/* Declarative data */
const char *declared_name; /* A string representing the command declared_name.
* It is a const char * for native commands and SDS for module commands. */
const char *summary; /* Summary of the command (optional). */
const char *complexity; /* Complexity description (optional). */
const char *since; /* Debut version of the command (optional). */
int doc_flags; /* Flags for documentation (see CMD_DOC_*). */
const char *replaced_by; /* In case the command is deprecated, this is the successor command. */
const char *deprecated_since; /* In case the command is deprecated, when did it happen? */
redisCommandGroup group; /* Command group */
commandHistory *history; /* History of the command */
int num_history;
const char **tips; /* An array of strings that are meant to be tips for clients/proxies regarding this command */
int num_tips;
redisCommandProc *proc; /* Command implementation */
int arity; /* Number of arguments, it is possible to use -N to say >= N */
uint64_t flags; /* Command flags, see CMD_*. */
uint64_t acl_categories; /* ACl categories, see ACL_CATEGORY_*. */
keySpec *key_specs;
int key_specs_num;
/* Use a function to determine keys arguments in a command line.
* Used for Redis Cluster redirect (may be NULL) */
redisGetKeysProc *getkeys_proc;
int num_args; /* Length of args array. */
/* Array of subcommands (may be NULL) */
struct redisCommand *subcommands;
/* Array of arguments (may be NULL) */
struct redisCommandArg *args;

几个容易看漏的点:

  • declared_name 是小写的。commands.def 里写的是 MAKE_CMD("get",...),不是 "GET"。
    命令名在运行时统一小写,查表时大小写不敏感(见 7.5 节)。
  • arity 可以是负数。2 表示恰好两个参数(GET key),-2 表示至少两个
    (SET key val [NX|XX] ...)。这是 GET 与 SET 的关键区别。
  • getkeys_proc 是一个可选的函数指针。有些命令的 key 位置不规则(比如 ZADD 的
    INCR 选项、GEORADIUS 的 STORE/STOREDIST),静态描述不了,就给一个运行期函数。
    commands.def 里 ZADD 那条的 get_keys 位置就是 zaddGetKeys 这样的函数名。
  • subcommands 是数组,运行期还会再长出一个 subcommands_dict(见 7.5 节)。

运行期部分(src/server.h:3243-3261):

// src/server.h:3243-3260
/* Runtime populated data */
long long microseconds, calls, rejected_calls, failed_calls;
long long slowlog_count, slowlog_time_us_sum, slowlog_time_us_max;
int id;     /* Command ID. This is a progressive ID starting from 0 that
                   is assigned at runtime, and is used in order to check
                   ACLs. A connection is able to execute a given command if
                   the user associated to the connection has this command
                   bit set in the bitmap of allowed commands. */
sds fullname; /* A SDS string representing the command fullname. */
struct hdr_histogram* latency_histogram; /*points to the command latency command histogram (unit of time nanosecond) */
keySpec legacy_range_key_spec; /* The legacy (first,last,step) key spec is
                                     * still maintained (if applicable) so that
                                     * we can still support the reply format of
                                     * COMMAND INFO and COMMAND GETKEYS */
dict *subcommands_dict; /* A dictionary that holds the subcommands, the key is the subcommand sds name
                             * (not the fullname), and the value is the redisCommand structure pointer. */
struct redisCommand *parent;
struct RedisModuleCommand *module_cmd; /* A pointer to the module command data (NULL if native command) */

calls / rejected_calls / failed_calls / microseconds 是每个命令的运行时统计,
COMMANDSTAT 读的就是它们。latency_histogram 是每命令一个 HDR 直方图,
第一次执行该命令时才分配(见 7.6 节 populateCommandStructure)。

从静态数组到 dict:populateCommandTable

生成的 commands.def 展开后是一个静态数组 redisCommandTable[]。
但运行时查命令用的是 dict。填表的函数在 src/server.c:3620-3645:

// src/server.c:3620-3645
extern struct redisCommand redisCommandTable[];

/* Populates the Redis Command Table dict from the static table in commands.c
 * which is auto generated from the json files in the commands folder. */
void populateCommandTable(void) {
    int j;
    struct redisCommand *c;

    for (j = 0;; j++) {
        c = redisCommandTable + j;
        if (c->declared_name == NULL)
            break;

        int retval1, retval2;

        c->fullname = sdsnew(c->declared_name);
        if (populateCommandStructure(c) == C_ERR)
            continue;

        retval1 = dictAdd(server.commands, sdsdup(c->fullname), c);
        /* Populate an additional dictionary that will be unaffected
         * by rename-command statements in redis.conf. */
        retval2 = dictAdd(server.orig_commands, sdsdup(c->fullname), c);
        serverAssert(retval1 == DICT_OK && retval2 == DICT_OK);
    }
}

三个要点:

  1. 数组以 declared_name == NULL 结尾,靠哨兵结束遍历,不存长度。
  2. 填了两个 dict:server.commands(当前生效的)和 server.orig_commands
    (不受 rename-command 影响的原始表)。rename-command 只会从前者里改名,
    后者保留原名 —— 这样重写过的命令向量还能找回原命令指针。
  3. 遍历时调 populateCommandStructure(c),失败就跳过这条命令。

两个 dict 在 src/server.c:2613-2614 创建,用的是同一个 dict 类型:

// src/server.c:2613-2614
    server.commands = dictCreate(&commandTableDictType);
    server.orig_commands = dictCreate(&commandTableDictType);

dict 类型定义在 src/server.c:663-673:

// src/server.c:663-673
/* Command table. sds string -> command struct pointer. */
dictType commandTableDictType = {
    dictSdsCaseHash,            /* hash function */
    NULL,                       /* key dup */
    NULL,                       /* val dup */
    dictSdsKeyCaseCompare,      /* key compare */
    dictSdsDestructor,          /* key destructor */
    NULL,                       /* val destructor */
    NULL,                       /* allow to expand */
    .force_full_rehash = 1,     /* force full rehashing */
};

dictSdsCaseHash 和 dictSdsKeyCaseCompare —— 哈希和比较都忽略大小写。
这就是「Redis 命令名大小写不敏感」的实现:客户端发 get、GET、Get 都能查到同一条命令。

.force_full_rehash = 1 表示这个 dict 不做渐进式 rehash,每次扩容都整体重算 ——
命令表是一次性填满、之后不再插入的,没必要为增量插入优化。

populateCommandStructure:填运行期字段

populateCommandTable 里调的 populateCommandStructure 在 src/server.c:3581-3618:

// src/server.c:3581-3618
int populateCommandStructure(struct redisCommand *c) {
    /* If the command marks with CMD_SENTINEL, it exists in sentinel. */
    if (!(c->flags & CMD_SENTINEL) && server.sentinel_mode)
        return C_ERR;

    /* If the command marks with CMD_ONLY_SENTINEL, it only exists in sentinel. */
    if (c->flags & CMD_ONLY_SENTINEL && !server.sentinel_mode)
        return C_ERR;

    /* Translate the command string flags description into an actual
     * set of flags. */
    setImplicitACLCategories(c);

    /* We start with an unallocated histogram and only allocate memory when a command
     * has been issued for the first time */
    c->latency_histogram = NULL;

    /* Handle the legacy range spec and the "movablekeys" flag (must be done after populating all key specs). */
    populateCommandLegacyRangeSpec(c);

    /* Assign the ID used for ACL. */
    c->id = ACLGetCommandID(c->fullname);

    /* Handle subcommands */
    if (c->subcommands) {
        for (int j = 0; c->subcommands[j].declared_name; j++) {
            struct redisCommand *sub = c->subcommands+j;

            sub->fullname = catSubCommandFullname(c->declared_name, sub->declared_name);
            if (populateCommandStructure(sub) == C_ERR)
                continue;

            commandAddSubcommand(c, sub, sub->declared_name);
        }
    }

    return C_OK;
}

这段代码回答了「JSON 里没有、但表里有的东西」:

  • Sentinel 模式裁剪命令:普通 Redis 里没有 SENTINEL 命令(CMD_SENTINEL),
    Sentinel 进程里则只有标了 CMD_SENTINEL 的命令。同一个二进制,两套命令表。
  • 隐式 ACL 类别:setImplicitACLCategories(c)(见 7.6 节)。
  • 延迟直方图懒分配:第一次执行该命令才建 HDR histogram。
  • 旧式 key spec 兼容:populateCommandLegacyRangeSpec(c) 从新的 key_specs 反推出
    老式的 firstkey/lastkey/keystep。
  • ACL ID:c->id = ACLGetCommandID(c->fullname) —— 每个命令在运行时分配一个递增 ID,
    ACL 靠这个 ID 做位图匹配(7.6 节)。

7.5 命令查找 —— lookupCommand

这一节回答:一条命令从 argv 到函数指针,经过几步?

主路径:lookupCommandLogic

命令表是 dict,所以查找就是一次 dict 查找。核心函数在 src/server.c:3739-3753:

// src/server.c:3739-3753
struct redisCommand *lookupCommandLogic(dict *commands, robj **argv, int argc, int strict) {
    struct redisCommand *base_cmd = dictFetchValue(commands, argv[0]->ptr);
    int has_subcommands = base_cmd && base_cmd->subcommands_dict;
    if (argc == 1 || !has_subcommands) {
        if (strict && argc != 1)
            return NULL;
        /* Note: It is possible that base_cmd->proc==NULL (e.g. CONFIG) */
        return base_cmd;
    } else { /* argc > 1 && has_subcommands */
        if (strict && argc != 2)
            return NULL;
        /* Note: Currently we support just one level of subcommands */
        return lookupSubcommand(base_cmd, argv[1]->ptr);
    }
}

流程图:

lookupCommand(argv, argc)
  └─ lookupCommandLogic(server.commands, argv, argc, strict=0)
       ├─ dictFetchValue(server.commands, argv[0])   ← 第一级:按命令名查父命令
       ├─ 有 subcommands_dict 且 argc > 1?
       │    └─ 是 → lookupSubcommand(base_cmd, argv[1])
       │              └─ dictFetchValue(base_cmd->subcommands_dict, argv[1])  ← 第二级
       └─ 否 → 直接返回 base_cmd

只有两级。代码里两处注释都强调了这一点(src/server.c:3750:「Currently we support just
one level of subcommands」)。Redis 的命令体系里没有三层嵌套。

strict 参数的语义在函数头的注释里(src/server.c:3731-3738):

// src/server.c:3731-3738
/* Look up a command by argv and argc
 *
 * If `strict` is not 0 we expect argc to be exact (i.e. argc==2
 * for a subcommand and argc==1 for a top-level command)
 * `strict` should be used every time we want to look up a command
 * name (e.g. in COMMAND INFO) rather than to find the command
 * a user requested to execute (in processCommand).
 */
  • strict = 0:宽松。用户输入 OBJECT(不带子命令)时,返回父命令 OBJECT,
    由后面的检查去报「这个命令需要子命令」。
  • strict = 1:严格。COMMAND INFO OBJECT 这种场合,参数个数必须精确匹配,
    否则返回 NULL。

包装函数(src/server.c:3755-3757):

// src/server.c:3755-3757
struct redisCommand *lookupCommand(robj **argv, int argc) {
    return lookupCommandLogic(server.commands,argv,argc,0);
}

lookupCommand 就是宽松模式,执行路径用它。

一组按名字查的变体

src/server.h:4022-4027 声明了 6 个查找入口:

// src/server.h:4022-4027
struct redisCommand *lookupCommand(robj **argv, int argc);
struct redisCommand *lookupCommandBySdsLogic(dict *commands, sds s);
struct redisCommand *lookupCommandBySds(sds s);
struct redisCommand *lookupCommandByCStringLogic(dict *commands, const char *s);
struct redisCommand *lookupCommandByCString(const char *s);
struct redisCommand *lookupCommandOrOriginal(robj **argv, int argc);

lookupCommandBySdsLogic 处理的是带竖线的全名(src/server.c:3759-3770):

// src/server.c:3759-3768
struct redisCommand *lookupCommandBySdsLogic(dict *commands, sds s) {
    int argc, j;
    sds *strings = sdssplitlen(s,sdslen(s),"|",1,&argc);
    if (strings == NULL)
        return NULL;
    if (argc < 1 || argc > 2) {
        /* Currently we support just one level of subcommands */
        sdsfreesplitres(strings,argc);
        return NULL;
    }

它把 object|encoding 按 | 切开,再造出 argv 走一遍严格查找。
竖线是子命令在命令表里的全名分隔符 —— fullname 就是这么拼出来的
(src/server.c:3541-3543):

// src/server.c:3541-3543
sds catSubCommandFullname(const char *parent_name, const char *sub_name) {
    return sdscatfmt(sdsempty(), "%s|%s", parent_name, sub_name);
}

lookupCommandOrOriginal:改名之后还能找到

src/server.c:3800-3812:

// src/server.c:3800-3812
/* Lookup the command in the current table, if not found also check in
 * the original table containing the original command names unaffected by
 * redis.conf rename-command statement.
 *
 * This is used by functions rewriting the argument vector such as
 * rewriteClientCommandVector() in order to set client->cmd pointer
 * correctly even if the command was renamed. */
struct redisCommand *lookupCommandOrOriginal(robj **argv ,int argc) {
    struct redisCommand *cmd = lookupCommandLogic(server.commands, argv, argc, 0);
    if (!cmd) cmd = lookupCommandLogic(server.orig_commands, argv, argc, 0);
    return cmd;
}

rename-command 在配置文件里改的是 server.commands 里的键;server.orig_commands
保留原名。所以一个被改名的命令,用原名依然能查到指针 —— 复制链路重放历史命令时要用到。

子命令的两级 dict

父命令的 subcommands_dict 在 src/server.c:3545-3553 建:

// src/server.c:3545-3553
void commandAddSubcommand(struct redisCommand *parent, struct redisCommand *subcommand, const char *declared_name) {
    if (!parent->subcommands_dict)
        parent->subcommands_dict = dictCreate(&commandTableDictType);

    subcommand->parent = parent; /* Assign the parent command */
    subcommand->id = ACLGetCommandID(subcommand->fullname); /* Assign the ID used for ACL. */

    serverAssert(dictAdd(parent->subcommands_dict, sdsnew(declared_name), subcommand) == DICT_OK);
}

键是子命令的短名(encoding,不是 object|encoding),值是 redisCommand*。
子命令的 fullname 才是全名。

查子命令(src/server.c:3727-3729):

// src/server.c:3727-3729
struct redisCommand *lookupSubcommand(struct redisCommand *container, sds sub_name) {
    return dictFetchValue(container->subcommands_dict, sub_name);
}

一次 dictFetchValue。

isContainerCommandBySds

还有一个判断「这是不是一个容器命令」的辅助函数(src/server.c:3721-3725):

// src/server.c:3721-3725
int isContainerCommandBySds(sds s) {
    struct redisCommand *base_cmd = dictFetchValue(server.commands, s);
    int has_subcommands = base_cmd && base_cmd->subcommands_dict;
    return has_subcommands;
}

用「有没有 subcommands_dict」来判定,而不是看 declared_name 里有没有竖线 ——
容器命令 OBJECT 本身没有子命令名,只能靠这个标志。

7.6 命令的 flag 与 ACL 类别

这一节回答:flags 和 acl_categories 是两套东西吗?

是两套,但有推导关系。

flag:命令的行为属性

flag 定义在 src/server.h:272-300,是一组位:

// src/server.h:272-300
#define CMD_WRITE (1ULL<<0)
#define CMD_READONLY (1ULL<<1)
#define CMD_DENYOOM (1ULL<<2)
#define CMD_MODULE (1ULL<<3)           /* Command exported by module. */
#define CMD_ADMIN (1ULL<<4)
#define CMD_PUBSUB (1ULL<<5)
#define CMD_NOSCRIPT (1ULL<<6)
#define CMD_BLOCKING (1ULL<<8)       /* Has potential to block. */
#define CMD_LOADING (1ULL<<9)
#define CMD_STALE (1ULL<<10)
#define CMD_SKIP_MONITOR (1ULL<<11)
#define CMD_SKIP_SLOWLOG (1ULL<<12)
#define CMD_ASKING (1ULL<<13)
#define CMD_FAST (1ULL<<14)
#define CMD_NO_AUTH (1ULL<<15)
#define CMD_MAY_REPLICATE (1ULL<<16)
#define CMD_SENTINEL (1ULL<<17)
#define CMD_ONLY_SENTINEL (1ULL<<18)
#define CMD_NO_MANDATORY_KEYS (1ULL<<19)
#define CMD_PROTECTED (1ULL<<20)
#define CMD_MODULE_GETKEYS (1ULL<<21)  /* Use the modules getkeys interface. */
#define CMD_MODULE_NO_CLUSTER (1ULL<<22) /* Deny on Redis Cluster. */
#define CMD_NO_ASYNC_LOADING (1ULL<<23)
#define CMD_NO_MULTI (1ULL<<24)
#define CMD_MOVABLE_KEYS (1ULL<<25) /* The legacy range spec doesn't cover all keys.
                                     * Populated by populateCommandLegacyRangeSpec. */
#define CMD_ALLOW_BUSY ((1ULL<<26))
#define CMD_MODULE_GETCHANNELS (1ULL<<27)  /* Use the modules getchannels interface. */
#define CMD_TOUCHES_ARBITRARY_KEYS (1ULL<<28)

注意 bit 7 跳过了 —— (1ULL<<7) 没有定义。别以为漏看了。

flag 决定的是运行时行为:这条命令会不会写数据(CMD_WRITE)、内存超限要不要拒绝
(CMD_DENYOOM)、能不能在加载 RDB 时执行(CMD_LOADING)、能不能在副本上执行
(CMD_READONLY)、会不会阻塞客户端(CMD_BLOCKING)。

src/server.h:3119-3168 有一整段注释逐条解释这些 flag 的含义,例如:

// src/server.h:3127-3146
 *
 * CMD_DENYOOM:     May increase memory usage once called. Don't allow if out
 *                  of memory.
 *
 * CMD_ADMIN:       Administrative command, like SAVE or SHUTDOWN.
 *
 * CMD_PUBSUB:      Pub/Sub related command.
 *
 * CMD_NOSCRIPT:    Command not allowed in scripts.
 *
 * CMD_BLOCKING:    The command has the potential to block the client.
 *
 * CMD_LOADING:     Allow the command while loading the database.
 *
 * CMD_NO_ASYNC_LOADING: Deny during async loading (when a replica uses diskless
 *                       sync swapdb, and allows access to the old dataset)
 *
 * CMD_STALE:       Allow the command while a slave has stale data but is not
 *                  allowed to serve this data. Normally no command is accepted
 *                  in this condition but just a few.

ACL 类别:命令的能力分组

ACL 类别是另一组位,定义在 src/server.h:305-328:

// src/server.h:304-329
/* Command flags that describe ACLs categories. */
#define ACL_CATEGORY_KEYSPACE (1ULL<<0)
#define ACL_CATEGORY_READ (1ULL<<1)
#define ACL_CATEGORY_WRITE (1ULL<<2)
#define ACL_CATEGORY_SET (1ULL<<3)
#define ACL_CATEGORY_SORTEDSET (1ULL<<4)
#define ACL_CATEGORY_LIST (1ULL<<5)
#define ACL_CATEGORY_HASH (1ULL<<6)
#define ACL_CATEGORY_STRING (1ULL<<7)
#define ACL_CATEGORY_BITMAP (1ULL<<8)
#define ACL_CATEGORY_HYPERLOGLOG (1ULL<<9)
#define ACL_CATEGORY_GEO (1ULL<<10)
#define ACL_CATEGORY_STREAM (1ULL<<11)
#define ACL_CATEGORY_PUBSUB (1ULL<<12)
#define ACL_CATEGORY_ADMIN (1ULL<<13)
#define ACL_CATEGORY_FAST (1ULL<<14)
#define ACL_CATEGORY_SLOW (1ULL<<15)
#define ACL_CATEGORY_BLOCKING (1ULL<<16)
#define ACL_CATEGORY_DANGEROUS (1ULL<<17)
#define ACL_CATEGORY_CONNECTION (1ULL<<18)
#define ACL_CATEGORY_TRANSACTION (1ULL<<19)
#define ACL_CATEGORY_SCRIPTING (1ULL<<20)
#define ACL_CATEGORY_ARRAY (1ULL<<21)
#ifdef ENABLE_GCRA
#define ACL_CATEGORY_RATE_LIMIT (1ULL<<22)
#endif

类别名到位的映射在 src/acl.c:54-81:

// src/acl.c:54-81
} ACLDefaultCommandCategories[] = { /* See redis.conf for details on each category. */
    {"keyspace", ACL_CATEGORY_KEYSPACE},
    {"read", ACL_CATEGORY_READ},
    {"write", ACL_CATEGORY_WRITE},
    {"set", ACL_CATEGORY_SET},
    {"sortedset", ACL_CATEGORY_SORTEDSET},
    {"list", ACL_CATEGORY_LIST},
    {"hash", ACL_CATEGORY_HASH},
    {"string", ACL_CATEGORY_STRING},
    {"array", ACL_CATEGORY_ARRAY},
    {"bitmap", ACL_CATEGORY_BITMAP},
    {"hyperloglog", ACL_CATEGORY_HYPERLOGLOG},
    {"geo", ACL_CATEGORY_GEO},
    {"stream", ACL_CATEGORY_STREAM},
    {"pubsub", ACL_CATEGORY_PUBSUB},
    {"admin", ACL_CATEGORY_ADMIN},
    {"fast", ACL_CATEGORY_FAST},
    {"slow", ACL_CATEGORY_SLOW},
    {"blocking", ACL_CATEGORY_BLOCKING},
    {"dangerous", ACL_CATEGORY_DANGEROUS},
    {"connection", ACL_CATEGORY_CONNECTION},
    {"transaction", ACL_CATEGORY_TRANSACTION},
    {"scripting", ACL_CATEGORY_SCRIPTING},
#ifdef ENABLE_GCRA
    {"ratelimit", ACL_CATEGORY_RATE_LIMIT},
#endif
    {NULL,0} /* Terminator. */
};

ACL_MAX_CATEGORIES 是 64(src/acl.c:49)—— 一共 64 位,够用。
@read、@write 这些字符串就是用户写在 ACL SETUSER 里的那些名字。

推导关系:setImplicitACLCategories

JSON 里只显式写了一部分类别。剩下的靠 flag 推导 —— src/server.c:3555-3575:

// src/server.c:3555-3575
/* Set implicit ACl categories (see comment above the definition of
 * struct redisCommand). */
void setImplicitACLCategories(struct redisCommand *c) {
    if (c->flags & CMD_WRITE)
        c->acl_categories |= ACL_CATEGORY_WRITE;
    /* Exclude scripting commands from the RO category. */
    if (c->flags & CMD_READONLY && !(c->acl_categories & ACL_CATEGORY_SCRIPTING))
        c->acl_categories |= ACL_CATEGORY_READ;
    if (c->flags & CMD_ADMIN)
        c->acl_categories |= ACL_CATEGORY_ADMIN|ACL_CATEGORY_DANGEROUS;
    if (c->flags & CMD_PUBSUB)
        c->acl_categories |= ACL_CATEGORY_PUBSUB;
    if (c->flags & CMD_FAST)
        c->acl_categories |= ACL_CATEGORY_FAST;
    if (c->flags & CMD_BLOCKING)
        c->acl_categories |= ACL_CATEGORY_BLOCKING;

    /* If it's not @fast is @slow in this binary world. */
    if (!(c->acl_categories & ACL_CATEGORY_FAST))
        c->acl_categories |= ACL_CATEGORY_SLOW;
}

六条推导规则,逐条读:

  1. CMD_WRITE → @write。
  2. CMD_READONLY → @read,但脚本类命令除外 —— 因为 EVAL 虽然只读,
    却能执行任意 Lua,危险得多,所以显式标了 @scripting 就不进 @read。
  3. CMD_ADMIN → @admin + @dangerous。
  4. CMD_PUBSUB → @pubsub。
  5. CMD_FAST → @fast。
  6. 不是 @fast 就是 @slow —— 二者互补,没有第三个选项。

第 6 条的注释说得很直白:「If it’s not @fast is @slow in this binary world.」
这个二元划分是硬编码在代码里的,不是配置。所以 @slow 永远不会是空的。

ACL 怎么用这些位

用户在 ACL SETUSER 里写 +@read +@string,最终落到命令 ID 位图上。
src/server.h:3246-3250 的注释说明了这条链:

// src/server.h:3246-3250
int id;     /* Command ID. This is a progressive ID starting from 0 that
                   is assigned at runtime, and is used in order to check
                   ACLs. A connection is able to execute a given command if
                   the user associated to the connection has this command
                   bit set in the bitmap of allowed commands. */

ACLGetCommandID(c->fullname) 在 populateCommandStructure 里给每条命令分配一个递增 ID。
用户 ACL 里存的是「允许的命令 ID 位图」+「允许的类别位图」,检查时把两者查表求并集。
命令 ID 是运行期分配的 —— 这就是为什么 ACL 检查不能编译期完成。

7.7 key spec:命令能碰哪些 key

这一节回答:key_specs 怎么描述「这条命令会碰哪些 key」?

为什么需要它

Redis Cluster 要判断一条命令的所有 key 是否落在同一个槽位(src/cluster_legacy.c 的槽位检查)。
要做到这点,必须知道命令的 key 在 argv 里的位置。

老办法是 firstkey / lastkey / keystep 三个整数:
「第一个 key 在第 1 个参数、最后一个 key 在第 2 个参数、每个 key 占 1 个参数」。
这个表达力太弱 —— ZADD 有 NX/XX/CH/INCR/GT/LT 选项,key 的位置不固定;
MSET 的 key 是 key1 val1 key2 val2 交替;GEORADIUS 的 key 后面还跟着 STORE 目标 key。

新的表达:两段式

新的 key_specs 是一个数组,每个元素描述「一组 key 的位置规则」,由两段组成:

  1. begin_search:从哪开始找。
  2. find_keys:怎么找(range 连续区间,还是 keynum 按个数算)。

keySpec 结构体在 src/server.h:3000-3043:

// src/server.h:3000-3043
    /* Declarative data */
    const char *notes;
    uint64_t flags;
    kspec_bs_type begin_search_type;
    union {
        struct {
            /* The index from which we start the search for keys */
            int pos;
        } index;
        struct {
            /* The keyword that indicates the beginning of key args */
            const char *keyword;
            /* An index in argv from which to start searching.
             * Can be negative, which means start search from the end, in reverse
             * (Example: -2 means to start in reverse from the penultimate arg) */
            int startfrom;
        } keyword;
    } bs;
    kspec_fk_type find_keys_type;
    union {
        /* NOTE: Indices in this struct are relative to the result of the begin_search step!
         * These are: range.lastkey, keynum.keynumidx, keynum.firstkey */
        struct {
            /* Index of the last key.
             * Can be negative, in which case it's not relative. -1 indicating till the last argument,
             * -2 one before the last and so on. */
            int lastkey;
            /* How many args should we skip after finding a key, in order to find the next one. */
            int keystep;
            /* If lastkey is -1, we use limit to stop the search by a factor. 0 and 1 mean no limit.
             * 2 means 1/2 of the remaining args, 3 means 1/3, and so on. */
            int limit;
        } range;
        struct {
            /* Index of the argument containing the number of keys to come */
            int keynumidx;
            /* Index of the fist key (Usually it's just after keynumidx, in
             * which case it should be set to keynumidx+1). */
            int firstkey;
            /* How many args should we skip after finding a key, in order to find the next one. */
            int keystep;
        } keynum;
    } fk;
} keySpec;

两个 union,每个 union 有两种形态:

bs(begin_search):

  • index.pos:固定位置。pos: 1 就是「argv[1] 是第一个 key」。
  • keyword.keyword + startfrom:按关键字定位。比如 SORT 的 BY/GET 选项之间夹着 key,
    就得先找到关键字再往后数。startfrom 可以是负数,表示从末尾倒着找
    (-2 = 从倒数第二个参数开始反向找)。

fk(find_keys):

  • range.lastkey / keystep / limit:连续区间。从 begin_search 的位置起,
    每 keystep 个参数取一个 key,直到第 lastkey 个。lastkey = 0 表示「只有第一个」。
    lastkey = -1 表示「一直到最后一个参数」。
  • keynum.keynumidx / firstkey / keystep:按个数。key 的个数由 argv 里某个位置的
    参数给出(比如 MGET 的 numkeys),先读那个数,再决定取几个。

注释里那句「Indices in this struct are relative to the result of the begin_search step!」
是关键:fk 里的下标是相对于 bs 找到的位置,不是相对于 argv 开头。

三个例子

GET(src/commands/get.json:16-35):从 argv[1] 开始,取 1 个,步长 1。

OBJECT ENCODING(src/commands/object-encoding.json:19-37):从 argv[2] 开始
(因为 argv[1] 是 ENCODING 这个子命令名),取 1 个,步长 1。

MSET:key 是 key1 val1 key2 val2 ... 交替,keynum 形态 ——
keynumidx 指向 numkeys 参数,firstkey 是它后面一个,keystep 是 2
(跳过一个 value)。自己去 src/commands/mset.json 看。

生成出来的样子

key_specs 在 commands.def 里是一个静态数组,名字是 <命令名>_Keyspecs。
GET 的在 src/commands.def 里的 GET_Keyspecs(在 src/commands.def:1-13834 之间的
key spec 段),引用它的地方是 commands.def:13806 那条 MAKE_CMD 的倒数第几段。

生成时按命令名大写命名(GET_Keyspecs),而 MAKE_CMD 里命令名本身是小写("get")。
这个大小写不一致是生成器的产物,不是笔误。

老式 spec 仍然保留

redisCommand 里有一个字段专门保留老式 spec(src/server.h:3253-3256):

// src/server.h:3253-3256
keySpec legacy_range_key_spec; /* The legacy (first,last,step) key spec is
                                     * still maintained (if applicable) so that
                                     * we can still support the reply format of
                                     * COMMAND INFO and COMMAND GETKEYS */

为什么要留:COMMAND INFO 和 COMMAND GETKEYS 的回复格式是对外的协议,
客户端库在解析。新老客户端都还在用,所以服务端继续输出老式的
firstkey/lastkey/keystep。populateCommandLegacyRangeSpec(c) 负责从新的
key_specs 反推出来。

redisCommand 里还有 getkeys_proc(src/server.h:3230-3232):

// src/server.h:3230-3232
/* Use a function to determine keys arguments in a command line.
* Used for Redis Cluster redirect (may be NULL) */
redisGetKeysProc *getkeys_proc;

有些命令连新的 key_specs 都表达不了 —— key 的位置取决于参数的值而不只是位置。
比如 ZADD 的 INCR 选项会把 member 变成另一个 key(ZADD zset INCR 1 member),
GEORADIUS 的 STORE 后面跟一个目标 key。这些命令给一个 C 函数,
运行期算。commands.def 里那条 MAKE_CMD 的 get_keys 位置填的就是这个函数名,
NULL 表示不需要。

7.8 与网文 / 7.x 的差异

这一节回答:按网上文章去找,会撞墙的地方在哪?

下表每一行都在 /work/ai/cwork/redis 这棵树上实测过:

事项 网文 / 7.x 的说法 这棵树的实际做法 依据
命令元数据在哪 手写在 src/commands.c 的 redisCommandTable[] 里 480 个 JSON → 生成 src/commands.def → src/commands.c 只剩一个 #include src/commands.c:1-13
命令表结构 静态数组,按名字排序,二分查找 dict(哈希表),大小写不敏感哈希与比较 src/server.c:663-673、src/server.c:3740
查找函数 lookupCommand 做二分查找 lookupCommand 转调 lookupCommandLogic,内部是 dictFetchValue src/server.c:3739-3757
命令名大小写 表里存小写,二分比较忽略大小写 表里存小写,dict 的哈希与比较函数 dictSdsCaseHash / dictSdsKeyCaseCompare 忽略大小写 src/server.c:663-673
命令改名 直接改数组里的名字 改 server.commands 的键,另存一份 server.orig_commands 保留原名 src/server.c:3639-3643、src/server.c:3807-3812
子命令怎么存 命令名带空格或用 ` ` 分隔的一整条 两级 dict:父命令在主表,子命令在 parent->subcommands_dict,键是短名
子命令支持几层 支持一层 只支持一层(代码里两处注释明说) src/server.c:3750、src/server.c:3765
key 位置怎么描述 firstkey / lastkey / keystep 三个整数 新的 key_specs(begin_search + find_keys 两段式),老的三个整数仍然保留给 COMMAND INFO 用 src/server.h:3000-3043、src/server.h:3253-3256
ACL 类别从哪来 大多手写在命令定义里 JSON 显式声明 + setImplicitACLCategories 按 flag 推导 src/server.c:3555-3575
@slow 是什么 一个普通类别 「不是 @fast 就是 @slow」,硬编码互补 src/server.c:3572-3574
Sentinel 命令表 同一个表 同一个二进制两套表:CMD_SENTINEL / CMD_ONLY_SENTINEL 决定这条命令在哪个进程里存在 src/server.c:3582-3588
命令 ID 编译期常量 运行期递增分配,ACLGetCommandID src/server.h:3246-3250、src/server.c:3602
回复 schema 没有 JSON 里有 reply_schema,但只在编译期开 LOG_REQ_RES 时才进二进制,尚未对外暴露 src/Makefile:406-412、src/commands/README.md:13-14

有几条值得单独说:

「命令表是 dict」这一条最容易踩。 网文(尤其是 6.x 时代的)会说「命令表是排序数组,
lookupCommand 用二分查找,复杂度 O(log n)」。这棵树里没有二分查找了 ——
lookupCommandLogic 第一行就是 dictFetchValue。如果你按二分查找去读代码,会找不到。

redisCommandTable[] 这个符号还在(src/server.c:3620 有 extern 声明),
但它现在只是生成物的静态数组,不是查询用的结构。真正的查询结构是 server.commands
这个 dict。看到这个符号还在,就以为「命令表还是数组」,是这棵树最常见的一个误判。

src/commands.c 只有 13 行。 网文会告诉你「命令表在 src/commands.c 里,
有一千多行」。这棵树里那个文件只有 13 行,全部内容是一个宏定义加一个 #include。

7.9 本章要点回顾

  1. 命令元数据是数据不是代码:480 个 JSON 在 src/commands/ 下,一个命令一个文件;
    子命令另开 父命令-子命令.json,用 container 字段指回父命令(src/commands/object-encoding.json:8)。
  2. 生成是机械的:utils/generate-command-code.py 读 JSON 产出 src/commands.def(13834 行);
    src/Makefile:515-516 定义了规则,而 commands.def 是签进仓库的,没 Python 也能编译。
  3. src/commands.c 只有 13 行 —— 一个 MAKE_CMD 宏加一个 #include "commands.def"。
    展开后是静态数组 redisCommandTable[]。
  4. 运行时查命令用的是 dict,不是数组:server.commands 与 server.orig_commands
    两个 dict,用 dictSdsCaseHash / dictSdsKeyCaseCompare,大小写不敏感
    (src/server.c:663-673)。
  5. lookupCommandLogic 只有两级:先查主表拿父命令,再看有没有 subcommands_dict
    决定要不要查第二级;只支持一层子命令(src/server.c:3739-3753)。
  6. strict 决定参数个数是否必须精确匹配:执行路径用宽松模式(lookupCommand),
    COMMAND INFO 这类场合用严格模式(lookupCommandBySds 系列)。
  7. rename-command 之后原名仍可查:server.orig_commands 保留原始名字,
    lookupCommandOrOriginal 先查现表再查原表(src/server.c:3807-3812)。
  8. flag 与 ACL 类别是两套位,但有推导关系:setImplicitACLCategories 把
    CMD_WRITE→@write、CMD_ADMIN→@admin+@dangerous、CMD_FAST→@fast;
    并且**「不是 @fast 就是 @slow」是硬编码的**(src/server.c:3555-3575)。
  9. JSON 里没有、但表里有的东西:CMD_SENTINEL 决定命令在 Sentinel 进程里存不存在;
    运行期分配的 ACL 命令 ID;懒分配的延迟直方图;从 key_specs 反推的老式
    firstkey/lastkey/keystep。
  10. key_specs 是两段式:begin_search 说从哪开始(固定下标或按关键字),
    find_keys 说怎么找(连续区间或按个数);fk 里的下标是相对 bs 结果的
    (src/server.h:3000-3043)。位置取决于参数值的命令另有 getkeys_proc 兜底。

7.10 接下来

下一篇 08 一次命令的完整生命周期 接着本文往下走:
本文把「命令怎么被找到」讲完了 —— 从 argv[0] 到 struct redisCommand *,
中间是一次 dict 查找加至多一次子命令查找。

但找到命令只是开始。接下来会发生什么?

  • 一条命令在真正执行之前要过多少道检查(参数个数、加载中、只读副本、内存超限、
    ACL、副本数不足、持久化错误);
  • 过期键是在哪一步被「顺手删掉」的;
  • call() 执行完命令之后,Redis 记了哪些账(调用次数、耗时、脏计数、慢日志);
  • 写命令怎么进复制流;
  • 回复是怎么拼出来、写回 socket 的;
  • 以及一条命令被拒绝的时候,分别回什么错误串。

引用

本文涉及的结构体、宏与函数,均取自 Redis 源码
(/work/ai/cwork/redis,分支 unstable,
git describe --tags = 8.12-m02-int-184-gff28c55fc,HEAD = ff28c55f,
核对时间:2026-12-04):

事实 出处
src/commands/ 目录的 README:JSON 不供第三方直接使用 src/commands/README.md:1-9
reply_schema 是 JSON Schema,尚未对外暴露 src/commands/README.md:13-14
GET 的完整 JSON(summary / arity / function / flags / key_specs) src/commands/get.json:1-56
GET 的 reply_schema 段 src/commands/get.json:36-47
OBJECT 的 JSON 只有父命令的壳,arity 为 -2 src/commands/object.json:1-9
OBJECT ENCODING 的 JSON:container 字段与子命令命名 src/commands/object-encoding.json:1-18
commands.def 的生成规则(依赖 commands/*.json 与生成脚本) src/Makefile:512-522
LOG_REQ_RES 决定生成哪一份 .def src/Makefile:406-412
src/commands.c 全文:两个宏 + 一个 #include src/commands.c:1-13
MAKE_CMD 宏的参数表(22 个位置参数,group 被丢弃) src/commands.c:4
commands.def 的头部:自动生成标记与命令组字符串表 src/commands.def:1-36
GET 在 commands.def 里的 MAKE_CMD 条目 src/commands.def:13806
src/commands.def 共 13834 行 src/commands.def:1-13834
utils/generate-command-code.py 共 635 行 utils/generate-command-code.py:1-635
生成器把 command_flags 转成 CMD_* 位 utils/generate-command-code.py:399-400
生成器输出文件名由 --with-reply-schema 决定 utils/generate-command-code.py:578-581
struct redisCommand 的声明期字段 src/server.h:3209-3242
struct redisCommand 的运行期字段(含 ACL 命令 ID 说明) src/server.h:3243-3261
keySpec 结构体:begin_search 与 find_keys 两个 union src/server.h:3000-3043
CMD_* flag 的全部定义(注意 bit 7 跳过) src/server.h:272-300
CMD_* flag 的逐条语义注释 src/server.h:3119-3168
ACL_CATEGORY_* 的全部定义 src/server.h:305-328
ACL_MAX_CATEGORIES = 64 src/acl.c:49
类别名到位映射表 ACLDefaultCommandCategories src/acl.c:54-81
commandTableDictType:大小写不敏感的哈希与比较 src/server.c:663-673
server.commands 与 server.orig_commands 的创建 src/server.c:2613-2614
populateCommandTable:从静态数组填两个 dict src/server.c:3620-3645
populateCommandStructure:Sentinel 裁剪、隐式类别、直方图懒分配、ACL ID、子命令递归 src/server.c:3581-3618
setImplicitACLCategories:六条推导规则与 @fast/@slow 互补 src/server.c:3555-3575
commandAddSubcommand:子命令字典的键是短名 src/server.c:3545-3553
catSubCommandFullname:全名用 ` ` 拼接
lookupSubcommand:一次 dictFetchValue src/server.c:3727-3729
lookupCommandLogic:两级查找与 strict 语义 src/server.c:3731-3753
lookupCommand:宽松模式包装 src/server.c:3755-3757
lookupCommandBySdsLogic:按 ` ` 切开再严格查找
lookupCommandOrOriginal:改名后仍能按原名找到 src/server.c:3800-3812
isContainerCommandBySds:靠 subcommands_dict 判定容器命令 src/server.c:3721-3725
redisCommand 里保留的老式 key spec 字段 src/server.h:3253-3256
getkeys_proc:key 位置取决于参数值的命令的兜底 src/server.h:3230-3232
六个查找入口的声明 src/server.h:4022-4027

文章作者: growdu
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 growdu !
  目录