Redis SDS简介与定义
前言
Redis并未直接沿用C语言中以空字符结尾的传统字符数组来表示字符串,而是设计并实现了名为“简单动态字符串”(SDS)的抽象数据类型,将其作为内部默认的字符串处理方式。这一设计决策源于C原生字符串无法满足Redis在安全性、执行效率以及功能扩展性方面的特定需求。
SDS类型定义与Header结构
一、SDS 定义
在标准C语言中,字符串被定义为以'\0'(NULL结束符)结尾的字符数组,通常通过字符指针(char *)进行访问。由于该约定禁止在字符串中间出现字节0,因此C字符串无法有效存储包含任意二进制数据的内容。
二、SDS 类型定义与兼容性
typedef char *sds;

每个sds.h/sdshdr结构表示一个SDS的值
struct sdshdr{
//记录buf数组中已使用的字节的数量
//等于sds所保存字符串的长度
int len;
//记录buf中未使用的数据
int free;
//字符数组,用于保存字符串
}
* free 属性的值为0,表示这个SDS没有分配任何未使用的空间
* len 属性长度为5,表示这个SDS保存一个五字节长的字符串
* buf 属性是一个char类型的数组,数组的前5个字节分别保存了'R','e','d','i','s'五个字符,而最后一个字节则保存了空字符串'\0'
初学者可能会产生疑惑:既然SDS是独立的抽象类型,为何它看起来等同于char *?
实际上,SDS在类型层面与传统C语言字符串保持完全兼容,其基础类型定义同样为char *。这意味着在需要传入C语言字符串参数的场景下,可以直接传递SDS实例,无需进行额外的类型转换。
然而,SDS与普通的char *存在本质区别。SDS是“二进制安全”(Binary Safe)的,能够存储任意二进制数据,不再依赖'\0'来标识字符串结束。为此,SDS必须在头部(header)维护一个长度字段,以准确记录字符串的实际大小。
三、SDS Header 结构分析
/* Note: sdshdr5 is never used, we just access the flags byte directly.
* However is here to document the layout of type 5 SDS strings. */
struct __attribute__ ((__packed__)) sdshdr5 {
unsigned char flags; /* 3 lsb of type, and 5 msb of string length */
char buf[];
};
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[];
};
struct __attribute__ ((__packed__)) sdshdr16 {
uint16_t len; /* used */
uint16_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr32 {
uint32_t len; /* used */
uint32_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
struct __attribute__ ((__packed__)) sdshdr64 {
uint64_t len; /* used */
uint64_t alloc; /* excluding the header and null terminator */
unsigned char flags; /* 3 lsb of type, 5 unused bits */
char buf[];
};
为了优化内存使用,SDS设计了五种不同类型的Header结构。
一个完整的SDS字符串在内存中由前后相邻的两部分构成:
- 首先是Header部分,通常包含字符串实际长度(len)、最大分配容量(alloc)以及标志位(flags)。其中sdshdr5的结构较为特殊。
- 其次是字符数组部分。该数组的长度等于最大容量加1。真正有效的字符串数据长度通常小于最大容量,其后跟随的是未使用的空余字节(通常填充为0),这使得字符串在不重新分配内存的情况下可以进行有限的向后扩展。此外,在有效数据末尾还保留了一个ASCII码为0的'\0'字符,以确保与传统C字符串的兼容性。字符数组之所以比最大容量多出一个字节,正是为了在字符串达到最大容量时,仍有一个字节用于存放NULL结束符。
除sdshdr5外,其余四种Header结构均包含以下三个核心字段:
- len:记录字符串的实际长度,不包含末尾的NULL结束符。
- alloc:记录字符串的最大分配容量,不包含末尾多余的字节。
- flags:占用一个字节,其最低3位用于标识Header的具体类型。
在各Header的类型定义中,有几个关键细节值得注意:
- 所有Header定义均使用了__attribute__ ((packed))属性,旨在指示编译器以紧凑模式分配内存。若缺少此属性,编译器可能因对齐优化而在结构体字段间插入填充字节,导致Header与SDS数据部分无法紧密相邻,进而破坏通过固定偏移量(如向低地址方向偏移1个字节)获取flags字段的逻辑。
- 各Header定义末尾均包含一个未指定长度的字符数组char buf[]。这是C语言中的柔性数组(flexible array member)写法,仅能作为结构体的最后一个成员。此处它仅起标记作用,表明flags之后即为字符数组,并指明其在结构体中的偏移位置。在计算结构体大小时,buf不占用任何内存空间。例如,sizeof(struct sdshdr16)的结果为5字节,其中不含buf字段。
- sdshdr5与其他Header不同,它不包含alloc字段,而是利用flags的高5位来存储长度。因此,sdshdr5不支持预留空余空间,若字符串需动态增长,必须重新分配内存。这种设计使其更适合存储长度小于32字节的静态短字符串。
综上所述,SDS字符串的Header隐藏在真实数据的前方(低地址方向),这种布局带来两大优势:
- Header与数据紧邻,无需分割为两块独立内存空间进行分配,有助于减少内存碎片,提升存储效率(memory efficiency)。
- 尽管Header有多种类型,但SDS统一通过char *表达,并保持与C字符串的类型兼容。若SDS存储的是可打印字符串,可直接传递给C标准函数,如使用strcmp进行比较或使用printf进行输出。
SDS基础操作函数列表
理清了SDS的数据结构,其具体操作函数的实现逻辑便易于理解。
四、SDS 基础操作函数
- sdslen(const sds s):获取SDS字符串的实际长度。
- sdssetlen(sds s, size_t newlen):设置SDS字符串的新长度。
- sdsinclen(sds s, size_t inc):增加SDS字符串的长度。
- sdsalloc(const sds s):获取SDS字符串的最大分配容量。
- sdssetalloc(sds s, size_t newlen):设置SDS字符串的新容量。
- sdsavail(const sds s):获取SDS字符串的空余空间大小(即alloc - len)。
- sdsHdrSize(char type):根据Header类型返回Header的大小。
- sdsReqType(size_t string_size):根据字符串数据长度计算所需的Header类型。
SDS动态内存分配与回收策略
五、SDS 数组动态分配策略
Header中定义的多个字段,其中一个重要作用是实现字符串的灵活操作,同时最大限度地减少内存重新分配和回收带来的开销。
Redis针对SDS制定了如下内存分配策略:
- 当SDS的len属性值小于1MB时,Redis会分配与len相同大小的空闲空间(free space)。这种设计的逻辑在于:如果上次使用了len长度的空间,程序下次很可能也需要同等大小的空间,因此预先分配等量空间可作为缓冲。
- 当SDS的len属性值大于1MB时,程序将额外分配1MB的未使用空间。此时若继续按惯性预测分配等量空间,成本过高且不经济。因此,Redis将1MB设为阈值,低于阈值时按需分配,高于阈值时则固定增加1MB作为临界缓冲值。
Redis的内存回收策略如下:
- Redis采用惰性回收机制。当字符串变短时,多余的内存空间不会立即归还给操作系统,而是暂时保留。这种短暂的资源持有策略既能充分利用内存,又避免了频繁的系统调用浪费,是一种高效的设计思想。
综上所述,Redis通过高性能的字符串实现,将原本N次字符串操作必然导致的N次内存重新分配,优化为在最坏情况下最多发生N次重新分配,显著提升了性能。
/* Enlarge the free space at the end of the sds string so that the caller
* is sure that after calling this function can overwrite up to addlen
* bytes after the end of the string, plus one more byte for nul term.
*
* Note: this does not change the *length* of the sds string as returned
* by sdslen(), but only the free buffer space we have. */
sds sdsMakeRoomFor(sds s, size_t addlen) {
void *sh, *newsh;
size_t avail = sdsavail(s);
size_t len, newlen;
char type, oldtype = s[-1] & SDS_TYPE_MASK;
int hdrlen;
/* Return ASAP if there is enough space left. */
if (avail >= addlen) return s;
len = sdslen(s);
sh = (char*)s-sdsHdrSize(oldtype);
newlen = (len+addlen);
if (newlen < SDS_MAX_PREALLOC)
newlen *= 2;
else
newlen += SDS_MAX_PREALLOC;
type = sdsReqType(newlen);
/* Don't use type 5: the user is appending to the string and type 5 is
* not able to remember empty space, so sdsMakeRoomFor() must be called
* at every appending operation. */
if (type == SDS_TYPE_5) type = SDS_TYPE_8;
hdrlen = sdsHdrSize(type);
if (oldtype==type) {
newsh = s_realloc(sh, hdrlen+newlen+1);
if (newsh == NULL) return NULL;
s = (char*)newsh+hdrlen;
} else {
/* Since the header size changes, need to move the string forward,
* and can't use realloc */
newsh = s_malloc(hdrlen+newlen+1);
if (newsh == NULL) return NULL;
memcpy((char*)newsh+hdrlen, s, len+1);
s_free(sh);
s = (char*)newsh+hdrlen;
s[-1] = type;
sdssetlen(s, len);
}
sdssetalloc(s, newlen);
return s;
}
/* Reallocate the sds string so that it has no free space at the end. The
* contained string remains not altered, but next concatenation operations
* will require a reallocation.
*
* After the call, the passed sds string is no longer valid and all the
* references must be substituted with the new pointer returned by the call. */
sds sdsRemoveFreeSpace(sds s) {
void *sh, *newsh;
char type, oldtype = s[-1] & SDS_TYPE_MASK;
int hdrlen;
size_t len = sdslen(s);
sh = (char*)s-sdsHdrSize(oldtype);
type = sdsReqType(len);
hdrlen = sdsHdrSize(type);
if (oldtype==type) {
newsh = s_realloc(sh, hdrlen+len+1);
if (newsh == NULL) return NULL;
s = (char*)newsh+hdrlen;
} else {
newsh = s_malloc(hdrlen+len+1);
if (newsh == NULL) return NULL;
memcpy((char*)newsh+hdrlen, s, len+1);
s_free(sh);
s = (char*)newsh+hdrlen;
s[-1] = type;
sdssetlen(s, len);
}
sdssetalloc(s, len);
return s;
}
SDS核心特性与String命令关系
六、SDS 的核心特点
SDS(Simple Dynamic String)是Redis广泛使用的字符串结构,相较于其他语言环境中的字符串,它具有以下显著特点:
- 支持动态内存扩展。SDS内容可修改或追加,属于可变(mutable)类型,而非不可变(immutable)类型。
- 具备二进制安全性(Binary Safe)。SDS能够存储任意二进制数据,不受NULL字符限制。
- 与传统C语言字符串类型兼容。
- 支持预分配空间和懒惰释放,在内存紧张时也可缩减不必要的内存占用。
- 能够在常数时间复杂度内获取字符串长度。
- 通过边界检查杜绝缓冲区溢出风险。
七、SDS 与 String 命令的关系
127.0.0.1:6379> set test test
OK
127.0.0.1:6379> append test " test"
(integer) 9
127.0.0.1:6379> get test
"test test"
127.0.0.1:6379> setbit test 36 1
(integer) 0
127.0.0.1:6379> get test
"test(test"
127.0.0.1:6379> getrange test -5 -1
"(test"
- String类型的append操作底层使用SDS的sdscatlen函数来实现。
- setbit和getrange命令首先根据Key获取整个SDS字符串,随后从中选取或修改指定部分。由于SDS本质上是字符数组,对其局部进行操作相对简单。
然而,String类型在存储值为数字时,还支持incr、decr等特殊操作。此时内部存储并非SDS,setbit和getrange的实现逻辑也会有所不同。
总结
以上内容涵盖了SDS的核心机制。希望本文对读者学习或工作有所帮助,如有疑问欢迎留言交流,感谢支持。
参考文章
- http://blog.csdn.net/xiejingfa/article/details/50972592
- http://blog.csdn.net/acceptedxukai/article/details/17482611
- https://segmentfault.com/a/1190000003984537