Redis源码解析
一、src/server.c 中的redisCommandTable列出的所有redis支持的命令,其中字符串命令包括从get到mget;列表命令从rpush到rpoplpush;集合命令包括从sadd到sscan;有序集合命令从zadd到zscan;哈希表命令包括从hse到hscan;地理命令包括从geoadd到geodist;位操作从bitop到bitpos;HyperLogLog命令包含padd到pfmerge等。
二、每种存储类型对应的底层数据结构
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。- 字符串-->sds.c 简单动态字符串
struct __attribute__ ((__packed__)) sdshdr8 {
uint8_t len; /* used */
uint8_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
- 列表--> Quicklist.c 快表,一种双向链表和ziplist(压缩表)相结合的链表,存储的内容是zl(ziplist), ziplist由于是一整块连续内存,所以存储效率很高。但是,它不利于修改操作,每次数据变动都会引发一次内存的realloc。特别是当ziplist长度很长的时候,一次realloc可能会导致大批量的数据拷贝,进一步降低性能。
typedef struct quicklistNode {
struct quicklistNode *prev;
struct quicklistNode *next;
unsigned char *zl;
unsigned int sz; /* ziplist size in bytes */
unsigned int count : 16; /* count of items in ziplist */
unsigned int encoding : 2; /* RAW==1 or LZF==2 */
unsigned int container : 2; /* NONE==1 or ZIPLIST==2 */
unsigned int recompress : 1; /* was this node previous compressed? */
unsigned int attempted_compress : 1; /* node can't compress; too small */
unsigned int extra : 10; /* more bits to steal for future usage */
} quicklistNode;
- 哈希表-->Dict.c 字典
typedef struct dict {
dictType *type;
void *privdata;
dictht ht[2];
long rehashidx; /* rehashing not in progress if rehashidx == -1 */
unsigned long iterators; /* number of iterators currently running */
} dict;
- 有序集合-->T_zset.c ,用跳跃表skiplist,查找元素的平均复杂度为O(logn)
typedef struct zskiplist {
struct zskiplistNode *header, *tail;
unsigned long length;
int level;
} zskiplist;
typedef struct zskiplistNode {
sds ele;
double score;
struct zskiplistNode *backward;
struct zskiplistLevel {
struct zskiplistNode *forward;
unsigned int span;
} level[];
} zskiplistNode;
其余类型基本用的sds与dict相结合的方式。
