学习Redis之旅:理解Redis源码

Redis是一个开源、高性能的数据结构服务器,支持key-value常见操作,常用于缓存、消息队列、计数器等场景下。虽然Redis的使用比较灵活,但是想要深入了解Redis的底层原理,就需要阅读并理解Redis的源码。

本文将从Redis的存储结构、网络模型、事件驱动模型等多个方面,深入探讨Redis的底层实现,并尝试理解Redis源码。

一、存储结构

Redis在内存中管理数据,数据结构分为五种:String、Hash、List、Set、Zset。其中,String最为基础,其他四种数据结构均可以由String构建而成。

1、String

“`c

struct sdshdr {

int len; // 记录当前字符串长度

int free; // 记录当前sds字符串空闲空间长度

char buf[]; // 字符串内容

}

2、Hash```ctypedef struct dictEntry {    void *key;              // 键    union {        void *val;        uint64_t u64;        int64_t s64;        double d;    } v;                    // 值    struct dictEntry *next; /* 指向下一个哈希节点,形成拉链表 */} dictEntry;typedef struct dictht {    dictEntry **table;      // 哈希表数组    unsigned long size;     // 哈希表大小    unsigned long sizemask; // 哈希表大小掩码,用于计算索引值    unsigned long used;     // 哈希表已用节点数量} dictht;typedef struct dict {    dictType *type;         // 类型特定函数    void *privdata;         // 私有数据    dictht ht[2];           // 两个哈希表,一个平时使用,一个进行扩容或者缩容    long rehashidx;         // rehashes 链表索引    unsigned long iterators;    // 当前Dict被迭代器使用的数量} dict;

3、List

“`c

typedef struct listNode {

struct listNode *prev; // 前置节点

struct listNode *next; // 后置节点

void *value; // 值

} listNode;

typedef struct list {

listNode *head; // 表头节点

listNode *tl; // 表尾节点

void *(*dup)(void *ptr); // 对链表中的值进行复制的函数

void *(*free)(void *ptr); // 对链表中的值进行释放的函数

int (*match)(void *ptr, void *key); // 在函数中查找链表中值和给定值相等的元素

unsigned long len; // 列表所包含的节点数量

} list;

4、Set```ctypedef struct {     dict *dict;    // 使用字典实现} set;

5、Zset

“`c

typedef struct zskiplistNode {

double score; // 权重值

struct zskiplistNode *backward; // 前一个节点, 从高层链表索引时使用

struct zskiplistLevel { // 跳跃表索引

struct zskiplistNode *forward; // 下一个节点,从底层链表索引时使用

unsigned int span; // 索引区间包括span个元素

} level[]; // 该节点所拥有的层数

} zskiplistNode;

typedef struct zskiplist {

struct zskiplistNode *header, *tl; // 头尾指针

unsigned long length; // 长度

int level; // 层数

} zskiplist;

typedef struct zset {

zskiplist *zsl; // 成功列表

dict *dict; // 字典

} zset;

二、网络模型Redis采用I/O多路复用,实现单线程下的高并发访问。Redis基于Reactor模式,将所有网络操作都转化为事件,通过事件驱动处理网络请求。1、事件处理核心```cvoid aeMn(aeEventLoop *eventLoop) {    eventLoop->stop = 0;    while (!eventLoop->stop) {        aeProcessEvents(eventLoop, AE_ALL_EVENTS);    }}int aeProcessEvents(aeEventLoop *eventLoop, int flags) {    int processed = 0, numevents;    // 等待事件产生(可读可写可异常)    if (eventLoop->maxfd != -1 ||        (flags & AE_TIME_EVENTS) ||        (flags & AE_DONT_WT)) {        int j;        aeTimeEvent *shortest = NULL;        struct timeval tv, *tvp;        // 如果是使用事件轮询阻塞方式,那就需要加入超时时间        if (eventLoop->timeEventNext) {            shortest = eventLoop->timeEventNext;            long now_sec, now_ms;            aeGetTime(&now_sec, &now_ms);            tvp = &tv;            tvp->tv_sec = shortest->when_sec - now_sec;            if (shortest->when_ms                 tvp->tv_usec = (shortest->when_ms + 1000 - now_ms) * 1000;                tvp->tv_sec--;            } else {                tvp->tv_usec = (shortest->when_ms - now_ms) * 1000;            }            if (tvp->tv_sec tv_sec = 0;            if (tvp->tv_usec tv_usec = 0;        } else {            if (flags & AE_DONT_WT) {                tv.tv_sec = tv.tv_usec = 0;                tvp = &tv;            } else {                tvp = NULL;             }        }        // 多路复用        numevents = aeApiPoll(eventLoop, tvp);        // 遍历已注册的各个fd,如果该fd上有事件了则处理        for (j = 0; j             aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];            int mask = eventLoop->fired[j].mask;            int fd = eventLoop->fired[j].fd;            int fired = 0; // 用来记录事件是否已经触发            if (fe->mask & mask & AE_READABLE) {                fired = 1;                fe->rfileProc(eventLoop, fd, fe->clientData, mask);            }            if (fe->mask & mask & AE_WRITABLE) {                if (!fired || fe->wfileProc != fe->rfileProc)                    fe->wfileProc(eventLoop, fd, fe->clientData, mask);            }        }        processed += numevents;    }    // 处理用户传入的EventLoop事件    if (flags & AE_TIME_EVENTS)        processed += processTimeEvents(eventLoop);    return processed; }

2、文件事件处理器

“`c

int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask, aeFileProc *proc, void *clientData)

{

// 取出 fd 的结构

aeFileEvent *fe = &eventLoop->events[fd];

// 监听读写事件

if (aeApiAddEvent(eventLoop, fd, mask) == -1)

return AE_ERR;

// 设置 fd 的掩码

fe->mask |= mask;

if (mask & AE_READABLE) fe->rfileProc = proc;

if (mask & AE_WRITABLE) fe->wfileProc = proc;

fe->clientData = clientData;

if (fd > eventLoop->maxfd)

eventLoop->maxfd = fd;

return AE_OK;

}

三、事件驱动模型1、I/O多路复用```cint aeApiPoll(aeEventLoop *eventLoop, struct timeval *tvp) {    int j, numevents = 0;    // 执行多路复用    if (eventLoop->maxfd != -1) {        // 等待事件        int retval = select(eventLoop->maxfd+1, &eventLoop->rfds, &eventLoop->wfds, &eventLoop->efds, tvp);        //

香港服务器首选,2H2G首月10元开通。()提供简单好用,价格厚道的香港/美国云服务器和独立服务器。IDC+ISP+ICP资质。ARIN和APNIC会员。成熟技术团队15年行业经验。