你的位置:首页 > 软件开发 > 数据库 > redis 源码阅读 内部数据结构

redis 源码阅读 内部数据结构

发布时间:2016-07-24 10:00:24
redis的内部数据结构主要有:字符串,双端链表,字典,跳跃表。这里主要记录redise字符串的设计。相关的源码位于:src/sds.h 和 src/sds.c。 一 字符串 sds的结构体struct sdshdr {int len; // buf 已占用长度int fre ...

 

redis的内部数据结构主要有:字符串双端链表字典跳跃表。从这个结构可以看出,redis字符串和C的不一样,本质字符串是保存在内存的某一个位置,然后把它的指针放到buf上。.这种方式对于读取字符串的长度的很快,是O(1)。申请的策略在sdsMakeRoomFor中。如下是redis的源码。 
/* Create a new sds string with the content specified by the 'init' pointer* and 'initlen'.* If NULL is used for 'init' the string is initialized with zero bytes.** The string is always null-termined (all the sds strings are, always) so* even if you create an sds string with:** mystring = sdsnewlen("abc",3");** You can print the string with printf() as there is an implicit \0 at the* end of the string. However the string is binary safe and can contain* \0 characters in the middle, as the length is stored in the sds header. */sds sdsnewlen(const void *init, size_t initlen) {struct sdshdr *sh;if (init) {sh = zmalloc(sizeof(struct sdshdr)+initlen+1);} else {sh = zcalloc(sizeof(struct sdshdr)+initlen+1);}if (sh == NULL) return NULL;sh->len = initlen;sh->free = 0;if (initlen && init)memcpy(sh->buf, init, initlen);sh->buf[initlen] = '\0';return (char*)sh->buf;}/* Free an sds string. No operation is performed if 's' is NULL. */void sdsfree(sds s) {if (s == NULL) return;zfree(s-sizeof(struct sdshdr));}
其中zmalloc zcalloc 和zfree 是申请内存的。封装malloc和calloc,主要是考虑到跨平台的情况。不过从这个地方可以看出redis在对内存申请与释放到什么独到的管理方式。这种方式用sds字符串,一不小心就可能会内存泄漏了。  

原标题:redis 源码阅读 内部数据结构

关键词:Redis

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录