redis 数据结构与对象

redis 数据结构与对象

time:2026_2_27

SDS 动态字符串

SDS 和 c 中的string 并不相同

1
2
3
4
5
6
struct sdshdr{
int len;
int free;
char buf[]
}

内存分配

  1. 少于1MB 的时候发生扩容的时候,len 和free 长度相同,分配内存为 len+free+1
  2. 大于1MB len 为当前大小,free 固定为1MB 内存为 len(buf size)+ free(1MB)+1bt

其它特性

  1. SDS具有二进制安全,在记录字符串的时候,能够记录任意位置空格(string 所不具有的),并且通过约定在末尾加入空格的方式能够实现兼容string 实现string的相加等功能
  2. key 为SDS

链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
typedef struct listNode{
struct ListNode * prev;
struct ListNode * next;
void * value;
} listNode;

typedef struct list{
listNode *head;// 头
listNode *tail;//尾
unsigned long long ; // 长度

void *(*dup)(void * ptr);//复制
void *(*free)(void *free);// 释放
void *(* match)(void *match);//匹配
} list;

字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
typedef struct dictht{
dictEntry ** table;
unsigned long size;
unsigned long sizemask;

unsigned long used;
}dictht;

typedef struct dictEntry{
void *key;
union{
void *val;
uint64_tu64;
int64_ts64;
} v;
struct dictEntry *next; // 指向下一个行成表 可以解决相同键值保存的问题
}

![alt text](/img/notes/学习/redis设计与实现/image/截屏2026-02-27 16.38.23.png)

1
2
3
4
5
6
7
8
typedef struct dict{
dicType * type;
void *provdata;
dictht ht[2];

int trehashids;
}

数据扩容操作实现

队列

跳跃队列

元素