This README is just a fast quick start document. You can find more detailed documentation at http://redis.io.

What is Redis?

Redis is often referred as a data structures server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a server-client model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way.

Data structures implemented into Redis have a few special properties:

  • Redis cares to store them on disk, even if they are always served and modified into the server memory. This means that Redis is fast, but that is also non-volatile.
  • Implementation of data structures stress on memory efficiency, so data structures inside Redis will likely use less memory compared to the same data structure modeled using an high level programming language.
  • Redis offers a number of features that are natural to find in a database, like replication, tunable levels of durability, cluster, high availability.

Another good example is to think of Redis as a more complex version of memcached, where the operations are not just SETs and GETs, but operations to work with complex data types like Lists, Sets, ordered data structures, and so forth.

If you want to know more, this is a list of selected starting points:

Building Redis

Redis can be compiled and used on Linux, OSX, OpenBSD, NetBSD, FreeBSD. We support big endian and little endian architectures, and both 32 bit and 64 bit systems.

It may compile on Solaris derived systems (for instance SmartOS) but our support for this platform is best effort and Redis is not guaranteed to work as well as in Linux, OSX, and *BSD there.

It is as simple as:

% make

You can run a 32 bit Redis binary using:

% make 32bit

After building Redis, it is a good idea to test it using:

% make test

Fixing build problems with dependencies or cached build options

Redis has some dependencies which are included into the deps directory. make does not automatically rebuild dependencies even if something in the source code of dependencies changes.

When you update the source code with git pull or when code inside the dependencies tree is modified in any other way, make sure to use the following command in order to really clean everything and rebuild from scratch:

make distclean

This will clean: jemalloc, lua, hiredis, linenoise.

Also if you force certain build options like 32bit target, no C compiler optimizations (for debugging purposes), and other similar build time options, those options are cached indefinitely until you issue a make distclean command.

Fixing problems building 32 bit binaries

If after building Redis with a 32 bit target you need to rebuild it with a 64 bit target, or the other way around, you need to perform a make distclean in the root directory of the Redis distribution.

In case of build errors when trying to build a 32 bit binary of Redis, try the following steps:

  • Install the packages libc6-dev-i386 (also try g++-multilib).
  • Try using the following command line instead of make 32bit: make CFLAGS="-m32 -march=native" LDFLAGS="-m32"

Allocator

Selecting a non-default memory allocator when building Redis is done by setting the MALLOC environment variable. Redis is compiled and linked against libc malloc by default, with the exception of jemalloc being the default on Linux systems. This default was picked because jemalloc has proven to have fewer fragmentation problems than libc malloc.

To force compiling against libc malloc, use:

% make MALLOC=libc

To compile against jemalloc on Mac OS X systems, use:

% make MALLOC=jemalloc

Verbose build

Redis will build with a user friendly colorized output by default. If you want to see a more verbose output use the following:

% make V=1

Running Redis

To run Redis with the default configuration just type:

% cd src
% ./redis-server

If you want to provide your redis.conf, you have to run it using an additional parameter (the path of the configuration file):

% cd src
% ./redis-server /path/to/redis.conf

It is possible to alter the Redis configuration by passing parameters directly as options using the command line. Examples:

% ./redis-server --port 9999 --slaveof 127.0.0.1 6379
% ./redis-server /etc/redis/6379.conf --loglevel debug

All the options in redis.conf are also supported as options using the command line, with exactly the same name.

Playing with Redis

You can use redis-cli to play with Redis. Start a redis-server instance, then in another terminal try the following:

% cd src
% ./redis-cli
redis> ping
PONG
redis> set foo bar
OK
redis> get foo
"bar"
redis> incr mycounter
(integer) 1
redis> incr mycounter
(integer) 2
redis>

You can find the list of all the available commands at http://redis.io/commands.

Installing Redis

In order to install Redis binaries into /usr/local/bin just use:

% make install

You can use make PREFIX=/some/other/directory install if you wish to use a different destination.

Make install will just install binaries in your system, but will not configure init scripts and configuration files in the appropriate place. This is not needed if you want just to play a bit with Redis, but if you are installing it the proper way for a production system, we have a script doing this for Ubuntu and Debian systems:

% cd utils
% ./install_server.sh

The script will ask you a few questions and will setup everything you need to run Redis properly as a background daemon that will start again on system reboots.

You'll be able to stop and start Redis using the script named /etc/init.d/redis_<portnumber>, for instance /etc/init.d/redis_6379.

Code contributions

Note: by contributing code to the Redis project in any form, including sending a pull request via Github, a code fragment or patch via private email or public discussion groups, you agree to release your code under the terms of the BSD license that you can find in the COPYING file included in the Redis source distribution.

Please see the CONTRIBUTING file in this source distribution for more information.

Redis internals

If you are reading this README you are likely in front of a Github page or you just untarred the Redis distribution tar ball. In both the cases you are basically one step away from the source code, so here we explain the Redis source code layout, what is in each file as a general idea, the most important functions and structures inside the Redis server and so forth. We keep all the discussion at a high level without digging into the details since this document would be huge otherwise and our code base changes continuously, but a general idea should be a good starting point to understand more. Moreover most of the code is heavily commented and easy to follow.

Source code layout

The Redis root directory just contains this README, the Makefile which calls the real Makefile inside the src directory and an example configuration for Redis and Sentinel. You can find a few shell scripts that are used in order to execute the Redis, Redis Cluster and Redis Sentinel unit tests, which are implemented inside the tests directory.

Inside the root are the following important directories:

  • src: contains the Redis implementation, written in C.
  • tests: contains the unit tests, implemented in Tcl.
  • deps: contains libraries Redis uses. Everything needed to compile Redis is inside this directory; your system just needs to provide libc, a POSIX compatible interface and a C compiler. Notably deps contains a copy of jemalloc, which is the default allocator of Redis under Linux. Note that under deps there are also things which started with the Redis project, but for which the main repository is not anitrez/redis. An exception to this rule is deps/geohash-int which is the low level geocoding library used by Redis: it originated from a different project, but at this point it diverged so much that it is developed as a separated entity directly inside the Redis repository.

There are a few more directories but they are not very important for our goals here. We'll focus mostly on src, where the Redis implementation is contained, exploring what there is inside each file. The order in which files are exposed is the logical one to follow in order to disclose different layers of complexity incrementally.

Note: lately Redis was refactored quite a bit. Function names and file names have been changed, so you may find that this documentation reflects the unstable branch more closely. For instance in Redis 3.0 the server.c and server.h files were named to redis.c and redis.h. However the overall structure is the same. Keep in mind that all the new developments and pull requests should be performed against the unstable branch.

server.h

The simplest way to understand how a program works is to understand the data structures it uses. So we'll start from the main header file of Redis, which is server.h.

All the server configuration and in general all the shared state is defined in a global structure called server, of type struct redisServer. A few important fields in this structure are:

  • server.db is an array of Redis databases, where data is stored.
  • server.commands is the command table.
  • server.clients is a linked list of clients connected to the server.
  • server.master is a special client, the master, if the instance is a slave.

There are tons of other fields. Most fields are commented directly inside the structure definition.

Another important Redis data structure is the one defining a client. In the past it was called redisClient, now just client. The structure has many fields, here we'll just show the main ones:

struct client {
    int fd;
    sds querybuf;
    int argc;
    robj **argv;
    redisDb *db;
    int flags;
    list *reply;
    char buf[PROTO_REPLY_CHUNK_BYTES];
    ... many other fields ...
}

The client structure defines a connected client:

  • The fd field is the client socket file descriptor.
  • argc and argv are populated with the command the client is executing, so that functions implementing a given Redis command can read the arguments.
  • querybuf accumulates the requests from the client, which are parsed by the Redis server according to the Redis protocol and executed by calling the implementations of the commands the client is executing.
  • reply and buf are dynamic and static buffers that accumulate the replies the server sends to the client. These buffers are incrementally written to the socket as soon as the file descriptor is writable.

As you can see in the client structure above, arguments in a command are described as robj structures. The following is the full robj structure, which defines a Redis object:

typedef struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* lru time (relative to server.lruclock) */
    int refcount;
    void *ptr;
} robj;

Basically this structure can represent all the basic Redis data types like strings, lists, sets, sorted sets and so forth. The interesting thing is that it has a type field, so that it is possible to know what type a given object has, and a refcount, so that the same object can be referenced in multiple places without allocating it multiple times. Finally the ptr field points to the actual representation of the object, which might vary even for the same type, depending on the encoding used.

Redis objects are used extensively in the Redis internals, however in order to avoid the overhead of indirect accesses, recently in many places we just use plain dynamic strings not wrapped inside a Redis object.

server.c

This is the entry point of the Redis server, where the main() function is defined. The following are the most important steps in order to startup the Redis server.

  • initServerConfig() setups the default values of the server structure.
  • initServer() allocates the data structures needed to operate, setup the listening socket, and so forth.
  • aeMain() starts the event loop which listens for new connections.

There are two special functions called periodically by the event loop:

  1. serverCron() is called periodically (according to server.hz frequency), and performs tasks that must be performed from time to time, like checking for timedout clients.
  2. beforeSleep() is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.

Inside server.c you can find code that handles other vital things of the Redis server:

  • call() is used in order to call a given command in the context of a given client.
  • activeExpireCycle() handles eviciton of keys with a time to live set via the EXPIRE command.
  • freeMemoryIfNeeded() is called when a new write command should be performed but Redis is out of memory according to the maxmemory directive.
  • The global variable redisCommandTable defines all the Redis commands, specifying the name of the command, the function implementing the command, the number of arguments required, and other properties of each command.

networking.c

This file defines all the I/O functions with clients, masters and slaves (which in Redis are just special clients):

  • createClient() allocates and initializes a new client.
  • the addReply*() family of functions are used by commands implementations in order to append data to the client structure, that will be transmitted to the client as a reply for a given command executed.
  • writeToClient() transmits the data pending in the output buffers to the client and is called by the writable event handler sendReplyToClient().
  • readQueryFromClient() is the readable event handler and accumulates data from read from the client into the query buffer.
  • processInputBuffer() is the entry point in order to parse the client query buffer according to the Redis protocol. Once commands are ready to be processed, it calls processCommand() which is defined inside server.c in order to actually execute the command.
  • freeClient() deallocates, disconnects and removes a client.

aof.c and rdb.c

As you can guess from the names these files implement the RDB and AOF persistence for Redis. Redis uses a persistence model based on the fork() system call in order to create a thread with the same (shared) memory content of the main Redis thread. This secondary thread dumps the content of the memory on disk. This is used by rdb.c to create the snapshots on disk and by aof.c in order to perform the AOF rewrite when the append only file gets too big.

The implementation inside aof.c has additional functions in order to implement an API that allows commands to append new commands into the AOF file as clients execute them.

The call() function defined inside server.c is responsible to call the functions that in turn will write the commands into the AOF.

db.c

Certain Redis commands operate on specific data types, others are general. Examples of generic commands are DEL and EXPIRE. They operate on keys and not on their values specifically. All those generic commands are defined inside db.c.

Moreover db.c implements an API in order to perform certain operations on the Redis dataset without directly accessing the internal data structures.

The most important functions inside db.c which are used in many commands implementations are the following:

  • lookupKeyRead() and lookupKeyWrite() are used in order to get a pointer to the value associated to a given key, or NULL if the key does not exist.
  • dbAdd() and its higher level counterpart setKey() create a new key in a Redis database.
  • dbDelete() removes a key and its associated value.
  • emptyDb() removes an entire single database or all the databases defined.

The rest of the file implements the generic commands exposed to the client.

object.c

The robj structure defining Redis objects was already described. Inside object.c there are all the functions that operate with Redis objects at a basic level, like functions to allocate new objects, handle the reference counting and so forth. Notable functions inside this file:

  • incrRefcount() and decrRefCount() are used in order to increment or decrement an object reference count. When it drops to 0 the object is finally freed.
  • createObject() allocates a new object. There are also specialized functions to allocate string objects having a specific content, like createStringObjectFromLongLong() and similar functions.

This file also implements the OBJECT command.

replication.c

This is one of the most complex files inside Redis, it is recommended to approach it only after getting a bit familiar with the rest of the code base. In this file there is the implementation of both the master and slave role of Redis.

One of the most important functions inside this file is replicationFeedSlaves() that writes commands to the clients representing slave instances connected to our master, so that the slaves can get the writes performed by the clients: this way their data set will remain synchronized with the one in the master.

This file also implements both the SYNC and PSYNC commands that are used in order to perform the first synchronization between masters and slaves, or to continue the replication after a disconnection.

Other C files

  • t_hash.c, t_list.c, t_set.c, t_string.c and t_zset.c contains the implementation of the Redis data types. They implement both an API to access a given data type, and the client commands implementations for these data types.
  • ae.c implements the Redis event loop, it's a self contained library which is simple to read and understand.
  • sds.c is the Redis string library, check http://github.com/antirez/sds for more information.
  • anet.c is a library to use POSIX networking in a simpler way compared to the raw interface exposed by the kernel.
  • dict.c is an implementation of a non-blocking hash table which rehashes incrementally.
  • scripting.c implements Lua scripting. It is completely self contained from the rest of the Redis implementation and is simple enough to understand if you are familar with the Lua API.
  • cluster.c implements the Redis Cluster. Probably a good read only after being very familiar with the rest of the Redis code base. If you want to read cluster.c make sure to read the Redis Cluster specification.

Anatomy of a Redis command

All the Redis commands are defined in the following way:

void foobarCommand(client *c) {
    printf("%s",c->argv[1]->ptr); /* Do something with the argument. */
    addReply(c,shared.ok); /* Reply something to the client. */
}

The command is then referenced inside server.c in the command table:

{"foobar",foobarCommand,2,"rtF",0,NULL,0,0,0,0,0},

In the above example 2 is the number of arguments the command takes, while "rtF" are the command flags, as documented in the command table top comment inside server.c.

After the command operates in some way, it returns a reply to the client, usually using addReply() or a similar function defined inside networking.c.

There are tons of commands implementations inside th Redis source code that can serve as examples of actual commands implementations. To write a few toy commands can be a good exercise to familiarize with the code base.

There are also many other files not described here, but it is useless to cover everything. We want to just help you with the first steps. Eventually you'll find your way inside the Redis code base :-)

Enjoy!



此README只是一个快速启动文档。您可以在 http://redis.io 上找到更详细的文档。

什么是Redis ?

Redis通常被称为数据结构服务器。这意味着Redis通过一组命令提供对可变数据结构的访问,这些命令使用具有TCP套接字和简单协议的服务器 - 客户端模型发送。所以不同的进程可以以共享的方式查询和修改相同的数据结构

在Redis中实现的数据结构有一些特殊属性:

  • Redis希望将它们存储在磁盘上,即使它们始终被服务并修改到服务器内存中。这意味着Redis很快,但也是非易失性的。
  • 数据结构的实现对存储器效率产生了压力,因此与使用高级编程语言建模的相同数据结构相比,Redis中的数据结构可能会使用更少的内存。
  • Redis提供了一些在数据库中自然找到的功能,如复制,可调节级别的耐用性,集群,高可用性。
另一个很好的例子是将Redis视为更复杂的memcached版本,其中的操作不仅仅是SET和GET,而是使用像列表,集合,有序数据结构等复杂数据类型的操作。

如果您想了解更多信息,这是所选出发点的列表:

建筑物Redis

Redis可以在Linux,OSX,OpenBSD,NetBSD,FreeBSD上编译和使用。 我们支持大端和小端的架构,同时支持32位 和64位系统。

它可以在Solaris派生系统(例如SmartOS)上编译,但我们的 对这个平台的支持是尽力而为,而且Redis并不保证 工作以及在Linux,OSX和* BSD那里。

很简单:

% make
您可以使用以下功能运行32位Redis二进制文件:

% make 32bit
在建立Redis之后,最好使用以下方法进行测试:

% make test

使用依赖关系或缓存构建选项修复构建问题

Redis具有包含在 deps 目录中的一些依赖项。 make 不会自动重建依赖关系,即使某些东西在 依赖关系的源代码更改。

当您使用 git pull 或代码中的代码更新源代码时 依赖树以任何其他方式修改,请确保使用以下 命令,以便真正清理所有内容并从头重建:

make distclean

这将清理:jemalloc,lua,hiredis,linenoise。

另外如果强制某些构建选项,如32位目标,则无C编译器 优化(用于调试目的)和其他类似构建时间选项, 这些选项将无限期缓存,直到您发出 make distclean 命令。

修复构建32位二进制文​​件的问题

如果在使用32位目标构建Redis之后,需要重建它 使用64位目标,或者相反,您需要执行一个 make distclean 在Redis发行版的根目录下。

如果在尝试构建Redis的32位二进制文​​件时出现构建错误,请尝试 以下步骤:

  • 安装软件包libc6-dev-i386(也尝试g ++ - multilib)。
  • 尝试使用以下命令行代替 make 32bit make CFLAGS = - m32 -march = nativeLDFLAGS = - m32

分配器

通过设置完成构建Redis时选择非默认内存分配器 环境变量 MALLOC 。 Redis被编译并链接到libc malloc默认情况下,除了jemalloc在Linux上是默认的 系统。这个默认值被选中,因为jemalloc已被证明是较少的 碎片问题比libc malloc。

要强制编译libc malloc,请使用:

% make MALLOC=libc

要在Mac OS X系统上编译jemalloc,请使用:

% make MALLOC=jemalloc

详细构建

默认情况下,Redis将使用友好的彩色输出构建。 如果要查看更详细的输出,请使用以下内容:

% make V=1

运行Redis

要使用默认配置运行Redis,只需键入:

% cd src
% ./redis-server

如果你想提供你的redis.conf,你必须使用额外的方法来运行它 参数(配置文件的路径):

% cd src
% ./redis-server /path/to/redis.conf

可以通过直接传递参数来更改Redis配置 作为使用命令行的选项。示例:

% ./redis-server --port 9999 --slaveof 127.0.0.1 6379
% ./redis-server /etc/redis/6379.conf --loglevel debug

redis.conf中的所有选项也可以使用该命令作为选项进行支持 行,具有完全相同的名称。

使用Redis

你可以使用redis-cli来玩Redis。启动一个redis-server实例, 然后在另一个终端尝试以下:

% cd src
% ./redis-cli
redis> ping
PONG
redis> set foo bar
OK
redis> get foo
"bar"
redis> incr mycounter
(integer) 1
redis> incr mycounter
(integer) 2
redis>

您可以在 http://redis.io/commands 找到所有可用命令的列表。

安装Redis

为了将Redis二进制文件安装到/ usr / local / bin中,只需使用:

% make install

如果您希望使用 make PREFIX = / some / other / directory install ,您可以使用 不同的目的地。

Make install只会在系统中安装二进制文件,但不会进行配置 init脚本和配置文件在适当的地方。这不是 如果你只想和Redis一起玩,但是如果你正在安装,则需要它 它是生产系统的正确方法,我们有一个这样做的脚本 对于Ubuntu和Debian系统:

% cd utils
% ./install_server.sh

脚本会询问您几个问题,并将设置您需要的一切 以正确的方式运行Redis作为后台进程将重新启动 系统重新启动。

您可以使用命名的脚本停止并启动Redis /etc/init.d/redis_<portnumber> ,例如 /etc/init.d/redis_6379

代码贡献

注意:通过以任何形式向Redis项目提供代码,包括发送 通过Github提取请求,通过私人电子邮件或代码片段或补丁 公开讨论组,您同意根据条款发布您的代码 您可以在Redis中包含的 COPYING 文件中找到BSD许可证 源分布。

请参阅此源代码发行版中的贡献文件以获取更多信息 信息。

Redis internals

如果您正在阅读本README,您可能在Github页面之前 或者你刚刚解开Redis分配焦油球。在这两种情况下 你基本上距离源代码一步之遥,所以在这里我们解释一下 Redis的源代码布局,在每个文件中作为一个总体思路是什么 Redis服务器内部最重要的功能和结构等等。 我们把所有的讨论都保持在一个很高的水平,而不是深入细节 因为这个文件会很大,否则我们的代码库会发生变化 不断,但一般的想法应该是一个很好的起点 了解更多此外,大部分代码都被大量评论和轻松 跟随。

源代码布局

Redis根目录只包含这个README,Makefile是 在 src 目录中调用真实的Makefile并提供一个示例 Redis和Sentinel的配置。你可以找到几个shell 用于执行Redis,Redis Cluster和 Redis Sentinel单元测试,在测试中实现 目录。

根目录中有以下重要目录:

  • src :包含用C编写的Redis实现
  • tests :包含在Tcl。
  • 中实现的单元测试
  • deps :包含Redis使用的库。所有需要编译Redis的内容都在这个目录下;您的系统只需要提供 libc ,POSIX兼容界面和C编译器。值得注意的是, deps 包含一个 jemalloc 的副本,这是Redis在Linux下的默认分配器。请注意,在 deps 下,还有一些以Redis项目开始的东西,但是主库不是 anitrez / redis 。这个规则是一个例外,它是Redis使用的低级地理编码库,它源于不同的项目,但是在这一点上它分歧很大,它被开发为分离的实体直接在Redis存储库中。

还有更多目录,但对我们的目标而言并不重要 这里。我们将主要关注包含Redis实现的 src 探索每个文件中的内容。文件的顺序 暴露是为了披露不同层次而遵循的逻辑 逐渐复杂。

注意:最近Redis被重构了很多。函数名和文件 名称已经更改,所以你可能会发现这个文档反映了 更加紧密地分配 unstable 分支。例如在Redis 3.0中的 server.c server.h 文件命名为 redis.c redis.h 。但总体来说 结构是一样的记住,所有的新发展和拉动 应该针对 unstable 分支执行请求。

server.h

了解程序如何工作的最简单的方法是了解 它使用的数据结构。所以我们将从主标题文件开始 Redis,它是 server.h

所有的服务器配置和一般所有的共享状态是 在名为 server 的全局结构中定义,类型为 struct redisServer 。 这个结构中的几个重要领域是:

  • server.db 是一组Redis数据库,其中存储数据。
  • server.commands 是命令表。
  • server.clients 是连接到服务器的客户端的链接列表。
  • server.master 是一个特殊的客户端,主机,如果实例是从机。
有很多其他领域。大多数字段都直接在里面注释 结构定义。

另一个重要的Redis数据结构就是定义一个客户端的数据结构。 在过去,它被称为 redisClient ,现在只是 client 。结构 有很多领域,这里我们将只显示主要的:

struct client {
    int fd;
    sds querybuf;
    int argc;
    robj **argv;
    redisDb *db;
    int flags;
    list *reply;
    char buf[PROTO_REPLY_CHUNK_BYTES];
    ... many other fields ...
}

客户端结构定义了连接的客户端:

  • fd 字段是客户端套接字文件描述符。
  • argc argv 填充客户端正在执行的命令,以便实现给定的Redis命令的函数可以读取参数。
  • querybuf 累积来自客户端的请求,这些请求由Redis服务器根据Redis协议解析,并通过调用客户端正在执行的命令的实现来执行。
  • 回复 buf 是积累服务器发送给客户端的回复的动态和静态缓冲区。只要文件描述符可写,这些缓冲区就会逐步写入套接字。

您可以在上面的客户端结构中看到命令中的参数 被描述为 robj 结构。以下是完整的 robj 结构,它定义了一个 Redis对象

typedef struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* lru time (relative to server.lruclock) */
    int refcount;
    void *ptr;
} robj;

这个结构基本上可以代表所有的基本的Redis数据类型 字符串,列表,集合,排序集等。有趣的是这个 它有一个类型字段,以便可以知道给定的类型 对象有一个 refcount ,以便可以引用相同的对象 在多个地方没有分配多次。最后是 ptr 字段指向对象的实际表示,这可能会有所不同 即使是相同的类型,这取决于使用的 encoding Redis对象在Redis内部使用广泛,但是按顺序 以避免间接访问的开销,最近在很多地方 我们只是使用不包含在Redis对象内的纯粹的动态字符串。

server.c

这是Redis服务器的入口点,其中 main()函数 被定义为。以下是启动时最重要的步骤 Redis服务器。

  • initServerConfig()设置服务器结构的默认值。
  • initServer()分配操作所需的数据结构,设置侦听套接字等。
  • aeMain()启动侦听新连接的事件循环。

事件循环定期有两个特殊功能:

  1. serverCron() is called periodically (according to server.hz frequency), and performs tasks that must be performed from time to time, like checking for timedout clients.
  2. beforeSleep() is called every time the event loop fired, Redis served a few requests, and is returning back into the event loop.

在server.c中,您可以找到处理Redis服务器其他重要内容的代码:

  • call()用于在给定客户端的上下文中调用给定的命令。
  • activeExpireCycle()通过 EXPIRE 命令处理具有时间设置密钥的密钥。
  • 当执行新的写入命令时,调用freeMemoryIfNeeded(),但根据 maxmemory 指令,Redis的内存不足。
  • 全局变量 redisCommandTable 定义了所有的Redis命令,指定命令的名称,实现命令的函数,所需的参数数以及每个命令的其他属性。

networking.c

该文件定义了客户机,主机和从机的所有I / O功能 (在Redis只是特殊客户):

  • createClient()分配并初始化新的客户端
  • addReply *()函数系列由命令实现使用,以便将数据附加到客户端结构中,这些数据将作为对执行的给定命令的回复发送到客户端。 / li> writeToClient()将输出缓冲区中的待处理数据发送给客户端,并由可写事件处理程序 sendReplyToClient()调用。
  • readQueryFromClient()是可读事件处理程序,并将从客户端读取的数据累加到查询缓冲区。
  • processInputBuffer()是根据Redis协议解析客户端查询缓冲区的入口点。一旦命令准备好处理,它就调用 server.c 中定义的 processCommand(),以便实际执行命令。
  • freeClient()取消分配,断开连接并删除客户端。

aof.c和rdb.c

您可以从名称中猜出这些文件实现RDB和AOF Redis的持久性。 Redis使用基于 fork()的持久性模型 系统调用以创建具有相同(共享)内存的线程 主要Redis线程的内容。此次要线程会转储内容 的磁盘上的内存。这由 rdb.c 用于创建快照 在磁盘上和通过 aof.c 为了执行AOF重写时 仅附加文件变得太大。

aof.c 中的实现具有附加功能 实现一个API,允许命令将新命令附加到AOF中 文件作为客户端执行它们。

server.c 内定义的 call()函数负责调用 这些功能又会将命令写入AOF。

db.c

某些Redis命令对特定的数据类型进行操作,另外一些则是通用的。 通用命令的示例是 DEL EXPIRE 。他们按键操作 而不是具体的他们的价值观。所有这些通用命令是 在 db.c 内定义。

另外,为了执行某些操作, db.c 实现了一个API 在Redis数据集上,而不直接访问内部数据结构。

在许多命令中使用的 db.c 中最重要的功能 实现如下:

  • lookupKeyRead() lookupKeyWrite()用于获取指向与给定键相关联的值的指针,或 NULL 如果密钥不存在。
  • dbAdd()及其较高级别的对应 setKey()在Redis数据库中创建一个新密钥。
  • dbDelete()删除一个键及其关联值。
  • emptyDb()删除整个单个数据库或定义的所有数据库。

该文件的其余部分实现了向客户端公开的通用命令。

object.c

已经描述了定义Redis对象的 robj 结构。内 object.c 有在Redis对象上操作的所有功能 一个基本的级别,像分配新对象的功能,处理引用 计数等等。此文件中的显着功能:

    使用
  • incrRefcount() decrRefCount()来增加或减少对象引用计数。当它下降到0时,对象终于被释放。
  • createObject()分配一个新对象。还有专门的功能来分配具有特定内容的字符串对象,如 createStringObjectFromLongLong()和类似的功能。

该文件还实现了 OBJECT 命令。

replication.c

这是Redis中最复杂的文件之一,建议使用 只有在熟悉其余代码库之后才能实现。 在这个文件中有执行主和从属的角色 的Redis。

此文件中最重要的功能之一是将代码写入命令到代表连接的从属实例的客户端的 replicationFeedSlaves() 给我们的主人,让奴隶可以得到客户的写作: 这样他们的数据集将保持与master中的数据集同步。

此文件还实现了 SYNC PSYNC 命令 用于执行主人之间的第一次同步 从站,或在断开连接后继续复制。

其他C文件

Redis命令的解剖

所有Redis命令的定义如下:

void foobarCommand(client *c) {
    printf("%s",c->argv[1]->ptr); /* Do something with the argument. */
    addReply(c,shared.ok); /* Reply something to the client. */
}

然后在命令表

server.c 中引用该命令
{"foobar",foobarCommand,2,"rtF",0,NULL,0,0,0,0,0},

在上面的例子中, 2 是命令占用的参数数, 而rtF是命令标志,如命令表中所述 server.c 中的顶级评论

命令以某种方式运行后,会向客户端返回答复, 通常使用 addReply()或在 networking.c 内定义的类似函数。

在Redis源代码中有大量的命令实现 这可以作为实际命令实现的示例。来写 一些玩具命令可以是一个很好的练习来熟悉代码库。

还有很多其他文件没有在这里描述,但是没有用 覆盖一切我们想要帮助您第一步。 最后你会发现你的方式在Redis代码库中: - )

享受!




相关问题推荐