Redis内存存储结构分析

五竹,20110418

Redis: A persistent key-value database with built-in net interface written in ANSI-C for Posix systems

1 Redis 内存存储结构

本文是基于 Redis-v2.2.4 版本进行分析.

1.1 Redis 内存存储总体结构

Redis 是支持多key-value数据库(表)的,并用 RedisDb 来表示一个key-value数据库(表). redisServer 中有一个 redisDb *db; 成员变量, RedisServer 在初始化时,会根据配置文件的 db 数量来创建一个 redisDb 数组. 客户端在连接后,通过 SELECT 指令来选择一个 reidsDb,如果不指定,则缺省是redisDb数组的第1个(即下标是 0 ) redisDb. 一个客户端在选择 redisDb 后,其后续操作都是在此 redisDb
上进行的. 下面会详细介绍一下 redisDb 的内存结构.

redis 的内存存储结构示意图

redisDb 的定义:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

typedef

struct

redisDb

{

dict
*dict;                
/*
The keyspace for this DB */

dict
*expires;             
/*
Timeout of keys with a timeout set */

dict
*blocking_keys;   
/*
Keys with clients waiting for data (BLPOP) */

dict
*io_keys;             
/*
Keys with clients waiting for VM I/O */

dict
*watched_keys;        
/*
WATCHED keys for MULTI/EXEC CAS */

int

id;

}
redisDb;

struct

redisDb 中 ,dict 成员是与实际存储数据相关的. dict 的定义如下:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

typedef

struct

dictEntry

{

void

*key;

void

*val;

struct

dictEntry *next;

}
dictEntry;

typedef

struct

dictType

{

unsigned
int

(*hashFunction)(
const

void

*key);

void

*(*keyDup)(
void

*privdata,
const

void

*key);

void

*(*valDup)(
void

*privdata,
const

void

*obj);

int

(*keyCompare)(
void

*privdata,
const

void

*key1,
const

void

*key2);

void

(*keyDestructor)(
void

*privdata,
void

*key);

void

(*valDestructor)(
void

*privdata,
void

*obj);

}
dictType;

/*
This is our hash table structure. Every dictionary has two of this as we

*
implement incremental rehashing, for the old to the new table. */

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];

int

rehashidx;
/*
rehashing not in progress if rehashidx == -1 */

int

iterators;
/*
number of iterators currently running */

}
dict;

dict 是主要是由 struct dictht 的 哈唏表构成的, 之所以定义成长度为2的( dictht ht[2] ) 哈唏表数组,是因为 redis 采用渐进的 rehash,即当需要 rehash 时,每次像 hset,hget 等操作前,先执行N 步 rehash. 这样就把原来一次性的 rehash过程拆散到进行, 防止一次性 rehash 期间 redis 服务能力大幅下降. 这种渐进的 rehash 需要一个额外的 struct dictht 结构来保存.

struct dictht 主要是由一个 struct dictEntry 指针数组组成的, hash 表的冲突是通过链表法来解决的.

struct dictEntry 中的 key 指针指向用 sds 类型表示的 key 字符串, val 指针指向一个 struct redisObject 结构体, 其定义如下:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

typedef

struct

redisObject

{

unsigned
type:4;

unsigned
storage:2;  
/*
REDIS_VM_MEMORY or REDIS_VM_SWAPPING */

unsigned
encoding:4;

unsigned
lru:22;       
/*
lru time (relative to server.lruclock) */

int

refcount;

void

*ptr;

/*
VM fields are only allocated if VM is active, otherwise the

*
object allocation function will just allocate

*
sizeof(redisObjct) minus sizeof(redisObjectVM), so using

*
Redis without VM active will not have any overhead. */

}
robj;

//type
占 4 bit,用来表示 key-value 中 value 值的类型,目前 redis 支持: string, list, set,zset,hash 5种类型的值.

/*
Object types */

#define
REDIS_STRING 0

#define
REDIS_LIST 1

#define
REDIS_SET 2

#define
REDIS_ZSET 3

#define
REDIS_HASH 4

#define
REDIS_VMPOINTER 8

//
storage 占 2 bit ,表示 此值是在 内存中,还是 swap 在硬盘上.

//
encoding 占 4 bit ,表示值的编码类型,目前有 8种类型:

/*
Objects encoding. Some kind of objects like Strings and Hashes can be

*
internally represented in multiple ways. The ‘encoding‘ field of the object

*
is set to one of this fields for this object. */

#define
REDIS_ENCODING_RAW 0     /* Raw representation */

#define
REDIS_ENCODING_INT 1     /* Encoded as integer */

#define
REDIS_ENCODING_HT 2      /* Encoded as hash table */

#define
REDIS_ENCODING_ZIPMAP 3  /* Encoded as zipmap */

#define
REDIS_ENCODING_LINKEDLIST 4 /* Encoded as regular linked list */

#define
REDIS_ENCODING_ZIPLIST 5 /* Encoded as ziplist */

#define
REDIS_ENCODING_INTSET 6  /* Encoded as intset */

#define
REDIS_ENCODING_SKIPLIST 7  /* Encoded as skiplist */

/*
如 type 是 REDIS_STRING 类型的,则其值如果是数字,就可以编码成 REDIS_ENCODING_INT,以节约内存.

*
如 type 是 REDIS_HASH 类型的,如果其 entry 小于配置值: hash-max-zipmap-entries 或 value字符串的长度小于 hash-max-zipmap-value, 则可以编码成 REDIS_ENCODING_ZIPMAP 类型存储,以节约内存. 否则采用 Dict 来存储.

*
如 type 是 REDIS_LIST 类型的,如果其 entry 小于配置值: list-max-ziplist-entries 或 value字符串的长度小于 list-max-ziplist-value, 则可以编码成 REDIS_ENCODING_ZIPLIST 类型存储,以节约内存; 否则采用 REDIS_ENCODING_LINKEDLIST 来存储.


如 type 是 REDIS_SET 类型的,如果其值可以表示成数字类型且 entry 小于配置值set-max-intset-entries, 则可以编码成 REDIS_ENCODING_INTSET 类型存储,以节约内存; 否则采用 Dict类型来存储.


lru: 是时间戳


refcount: 引用次数


void * ptr : 指向实际存储的 value 值内存块,其类型可以是 string, set, zset,list,hash ,编码方式可以是上述 encoding 表示的一种.

*
至于一个 key 的 value 采用哪种类型来保存,完全是由客户端的指令来决定的,如 hset ,则值是采用REDIS_HASH 类型表示的,至于那种编码(encoding),则由 redis 根据配置自动决定.

*/

1.2 Dict 结构

Dict 结构在<1.1Redis 内存存储结构>; 已经描述过了,这里不再赘述.

1.3 zipmap 结构

如果redisObject的type 成员值是 REDIS_HASH 类型的,则当该hash 的 entry 小于配置值: hash-max-zipmap-entries 或者value字符串的长度小于 hash-max-zipmap-value, 则可以编码成 REDIS_ENCODING_ZIPMAP 类型存储,以节约内存. 否则采用 Dict 来存储.

zipmap 其实质是用一个字符串数组来依次保存key和value,查询时是依次遍列每个 key-value 对,直到查到为止. 其结构示意图如下:

为了节约内存,这里使用了一些小技巧来保存 key 和 value 的长度. 如果 key 或 value 的长度小于ZIPMAP_BIGLEN(254),则用一个字节来表示,如果大于ZIPMAP_BIGLEN(254),则用5个字节保存,第一个字节为保存ZIPMAP_BIGLEN(254),后面4个字节保存 key或value 的长度.

  1. 初始化时只有2个字节,第1个字节表示 zipmap 保存的 key-value 对的个数(如果key-value 对的个数超过 254,则一直用254来表示, zipmap 中实际保存的 key-value 对个数可以通过 zipmapLen() 函数计算得到).
    • hset(nick,wuzhu) 后,

    • 第1个字节保存key-value 对(即 zipmap 的entry 数量)的数量1
    • 第2个字节保存key_len 值 4
    • 第3~6 保存 key “nick”
    • 第 7 字节保存 value_len 值 5
    • 第 8 字节保存空闭的字节数 0 (当 该 key 的值被重置时,其新值的长度与旧值的长度不一定相等,如果新值长度比旧值的长度大,则 realloc 扩大内存; 如果新值长度比旧值的长度小,且相差大于 4 bytes ,则 realloc 缩小内存,如果相差小于 4,则将值往前移,并用 empty_len 保存空闲的byte 数)
    • 第 9~13字节保存 value 值 “wuzhu”
  2. hset(age,30)

    插入 key-value 对 (“age”,30)
  3. hset(nick,tide)

    插入 key-value 对 (“nick”,”tide”), 后可以看到 empty_len 为1 ,

1.4 ziplist 结构

如果redisObject的type 成员值是 REDIS_LIST 类型的,则当该list 的 elem数小于配置值: hash-max-ziplist-entries 或者elem_value字符串的长度小于 hash-max-ziplist-value, 则可以编码成 REDIS_ENCODING_ZIPLIST 类型存储,以节约内存. 否则采用 list 来存储.

ziplist 其实质是用一个字符串数组形式的双向链表. 其结构示意图如下:

  1. ziplist header由3个字段组成:

    • ziplist_bytes: 用一个uint32_t 来保存, 构成 ziplist 的字符串数组的总长度,包括 ziplist header,
    • ziplist_tail_offset: 用一个uint32_t 来保存,记录 ziplist 的尾部偏移位置.
    • ziplist_length: 用一个 uint16_t 来保存,记录 ziplist 中 elem 的个数
  2. ziplist node 也由 3 部分组成:
    • prevrawlen: 保存上一个 ziplist node 的占用的字节数,包括: 保存prevarwlen,currawlen 的字节数和elem value 的字节数.
    • currawlen&encoding: 当前elem value 的raw 形式存款所需的字节数及在ziplist 中保存时的编码方式(例如,值可以转换成整数,如示意图中的”1024”, raw_len 是 4 字节,但在 ziplist 保存时转换成 uint16_t 来保存,占2 个字节).
    • (编码后的)value

可以通过 prevrawlen 和 currawlen&encoding 来遍列 ziplist.

ziplist 还能到一些小技巧来节约内存.

  • len 的存储: 如果 len 小于 ZIP_BIGLEN(254),则用一个字节来保存; 否则需要 5 个字节来保存,第 1 个字节存 ZIP_BIGLEN,作为标识符.
  • value 的存储: 如果 value 是数字类型的,则根据其值的范围转换成 ZIP_INT_16B, ZIP_INT_32B或ZIP_INT_64B 来保存,否则用 raw 形式保存.

1.5 adlist 结构


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

typedef

struct

listNode

{

struct

listNode *prev;

struct

listNode *next;

void

*value;

}
listNode;

typedef

struct

listIter

{

listNode
*next;

int

direction;

}
listIter;

typedef

struct

list

{

listNode
*head;

listNode
*tail;

void

*(*dup)(
void

*ptr);

void

(*
free)(void

*ptr);

int

(*match)(
void

*ptr,
void

*key);

unsigned
int

len;

}
list;

常见的双向链表,不作分析.

1.6 intset 结构

intset 是用一个有序的整数数组来实现集合(set). struct intset 的定义如下:


1

2

3

4

5

6

7

8

9

10

11

typedef

struct

intset

{

uint32_t
encoding;

uint32_t
length;

int8_t
contents[];

}
intset;

  • encoding: 来标识数组是 int16_t 类型, int32_t 类型还是 int64_t 类型的数组. 至于怎么先择是那种类型的数组,是根据其保存的值的取值范围来决定的,初始化时是 int16_t, 根据 set 中的最大值在 [INT16_MIN, INT16_MAX] , [INT32_MIN, INT32_MAX], [INT64_MIN, INT64_MAX]的那个取值范围来动态确定整个数组的类型. 例如set一开始是 int16_t 类型,当一个取值范围在 [INT32_MIN, INT32_MAX]的值加入到
    set 时,则将保存 set 的数组升级成 int32_t 的数组.
  • length: 表示 set 中值的个数
  • contents: 指向整数数组的指针

1.7 zset 结构

首先,介绍一下 skip list 的概念,然后再分析 zset 的实现.

1.7.1 Skip List 介绍

1.7.1.1 有序链表

1) Searching a key in a Sorted linked list


1

2

3

4

5

6

7

//Searching
an element <em>x</em>

cell
*p =head ;

while

(p->next->key < x )  p=p->next ;

return

p ;

Note: we return the element proceeding either the element containing x, or the smallest element with a key larger than x (if x does
not exists)

2) inserting a key into a Sorted linked list


1

2

3

4

5

6

7

8

9

10

11

//To
insert 35 -

p=find(35);

CELL
*p1 = (CELL *)
malloc(sizeof(CELL));

p1->key=35;

p1->next
= p->next ;

p->next 
= p1 ;

3) deleteing a key from a sorted list


1

2

3

4

5

6

7

8

9

//To
delete 37 -

p=find(37);

CELL
*p1 =p->next;

p->next
= p1->next ;

free(p1);

1.7.1.2 SkipList(跳跃表)定义

SKIP LIST : A data structure for maintaing a set of keys in a sorted order.

Consists of several levels.

All keys appear in level 1

Each level is a sorted list.

If key x appears in level i, then it also appears in all levels below i

An element in level i points (via down pointer) to the element with the same key in the level below.

In each level the keys and appear. (In our implementation, INT_MIN and INT_MAX

Top points to the smallest element in the highest level.

1.7.1.3 SkipList(跳跃表)操作

1) An empty SkipList

2) Finding an element with key x


1

2

3

4

5

6

7

8

9

10

11

12

13

p=top

While(1)

{

while

(p->next->key < x ) p=p->next;

If
(p->down == NULL )
return

p->next

p=p->down
;

}

Observe that we return x, if exists, or succ(x) if x is not in the SkipList

3) Inserting new element X

Determine k the number of levels in which x participates (explained later)

Do find(x), and insert x to the appropriate places in the lowest k levels. (after the elements at which the search path turns down or terminates)

Example – inserting 119. k=2

If k is larger than the current number of levels, add new levels (and update top)

Example – inser(119) when k=4

Determining k

k – the number of levels at which an element x participate.

Use a random function OurRnd() — returns 1 or 0 (True/False) with equal probability.

k=1 ;

While( OurRnd() ) k++ ;

Deleteing a key x

Find x in all the levels it participates, and delete it using the standard ‘delete from a linked list’ method.

If one or more of the upper levels are empty, remove them (and update top)

Facts about SkipList

The expected number of levels is O( log n )

(here n is the numer of elements)

The expected time for insert/delete/find is O( log n )

The expected size (number of cells) is O(n )

1.7.2 redis SkipList 实现

/* ZSETs use a specialized version of Skiplists */


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

typedef

struct

zskiplistNode

{

robj
*obj;

double

score;

struct

zskiplistNode *backward;

struct

zskiplistLevel

{

struct

zskiplistNode *forward;

unsigned
int

span;

}
level[];

}
zskiplistNode;

typedef

struct

zskiplist

{

struct

zskiplistNode *header, *tail;

unsigned
long

length;

int

level;

}
zskiplist;

typedef

struct

zset

{

dict
*dict;

zskiplist
*zsl;

}
zset;

zset 的实现用到了2个数据结构: hash_table 和 skip list (跳跃表),其中 hash table 是使用 redis 的 dict 来实现的,主要是为了保证查询效率为 O(1),而 skip list (跳跃表) 是用来保证元素有序并能够保证 INSERT 和 REMOVE 操作是 O(logn)的复杂度。

1) zset初始化状态

createZsetObject函数来创建并初始化一个 zset


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

robj
*createZsetObject(
void)

{

zset
*zs = zmalloc(
sizeof(*zs));

robj
*o;

zs->dict
= dictCreate(&zsetDictType,NULL);

zs->zsl
= zslCreate();

o
= createObject(REDIS_ZSET,zs);

o->encoding
= REDIS_ENCODING_SKIPLIST;

return

o;

}

zslCreate()函数用来创建并初如化一个 skiplist。 其中,skiplist 的 level 最大值为 ZSKIPLIST_MAXLEVEL=32 层。


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

zskiplist
*zslCreate(
void)

{

int

j;

zskiplist
*zsl;

zsl
= zmalloc(
sizeof(*zsl));

zsl->level
= 1;

zsl->length
= 0;

zsl->header
= zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);

for

(j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {

zsl->header->level[j].forward
= NULL;

zsl->header->level[j].span
= 0;

}

zsl->header->backward
= NULL;

zsl->tail
= NULL;

return

zsl;

}

2) ZADD myzset 1 “one”

ZADD 命令格式:

ZADD key score member

  1. 根据 key 从 redisDb 进行查询,返回 zset 对象。
  2. 以 member 作为 key,score 作为 value ,向 zset的 dict 进行中插入;
  3. 如果返回成功,表明 member 没有在 dict 中出现过,直接向 skiplist 进行插入。
  4. 如果步骤返回失败,表明以 member 已经在 dict中出现过,则需要先从 skiplist 中删除,然后以现在的 score 值重新插入。

3) ZADD myzset 3 “three”

4) ZADD myzset 2 “two”

Filed under - 其他 45
Comments
 so far.

标签:NoSQLredis

相关文章

时间: 2024-08-01 13:54:19

Redis内存存储结构分析的相关文章

Redis数据存储优化机制(转)

原文:Redis学习笔记4--Redis数据存储优化机制 1.zipmap优化hash: 前面谈到将一个对象存储在hash类型中会占用更少的内存,并且可以更方便的存取整个对象.省内存的原因是新建一个hash对象时开始是用zipmap来存储的.这个zipmap其实并不是hash table,但是zipmap相比正常的hash实现可以节省不少hash本身需要的一些元数据存储开销.尽管zipmap的添加,删除,查找都是O(n),但是由于一般对象的field数量都不太多.所以使用zipmap也是很快的,

如何用分布式缓存服务实现Redis内存优化

Redis是一种支持Key-Value等多种数据结构的存储系统,其数据特性是"ALL IN MEMORY",因此优化内存十分重要.在对Redis进行内存优化时,先要掌握Redis内存存储的特性比如字符串,压缩编码,整数集合等,再根据数据规模和所用命令需求去调整,从而达到空间和效率的最佳平衡. 但随着数据大幅增长,开发人员需要面对重新优化内存所带来开发和数据迁移的双重成本也越来越高.Redis所有的数据都在内存中,那么,我们是否可以通过简便高效的方式去实现Redis内存优化呢? 答案当然

Redis 内存使用优化与存储

Redis 常用数据类型Redis 最为常用的数据类型主要有以下五种:• String• Hash• List• Set• Sorted set在具体描述这几种数据类型之前,我们先通过一张图了解下 Redis 内部内存管理中是如何描述这些不同数据类型的:首先 Redis 内部使用一个 redisObject 对象来表示所有的 key 和 value,redisObject 最主要的信息如上图所示:... Redis 常用数据类型 Redis 最为常用的数据类型主要有以下五种: • String

Redis内存使用优化与存储

在具体描述这几种数据类型之前,我们先通过一张图了解下Redis内部内存管理中是如何描述这些不同数据类型的: 首先Redis内部使用一个redisObject对象来表示所有的key和value,redisObject最主要的信息如上图所示:type代表一个value对象具体是何种数据类型,encoding是不同数据类型在redis内部的存储方式,比如:type=string代表value存储的是一个普通字符串,那么对应的encoding可以是raw或者是int,如果是int则代表实际redis内部

NoSQL数据库:Redis内存使用优化与存储

Redis常用数据类型 Redis最为常用的数据类型主要有以下五种: ●String ●Hash ●List ●Set ●Sorted set 在具体描述这几种数据类型之前,我们先通过一张图了解下Redis内部内存管理中是如何描述这些不同数据类型的: 首先Redis内部使用一个redisObject对象来表示所有的key和value,redisObject最主要的信息如上图所示:type代表一个value对象具体是何种数据类型,encoding是不同数据类型在redis内部的存储方式,比如:ty

Redis数据存储解决方案

1.背景1.1 Redis简介 官方网站:http://redis.io/,Redis是REmote DIctionary Server的缩写. Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库,并提供多种语言的API.从2010年3月15日起,Redis的开发工作由VMware主持.它跟 memcached 类似,不过数据可以持久化,而且支持的数据类型很丰富.它在保持键值数据库简单快捷特点的同时,又吸收了部分关系数据库的优点.从而

Redis 内存管理与事件处理

1 Redis内存管理 Redis内存管理相关文件为zmalloc.c/zmalloc.h,其只是对C中内存管理函数做了简单的封装,屏蔽了底层平台的差异,并增加了内存使用情况统计的功能. void *zmalloc(size_t size) {    // 多申请的一部分内存用于存储当前分配了多少自己的内存     void *ptr = malloc(size+PREFIX_SIZE);      if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE

redis内存优化、持久化以及主从复制

Redis 数据库内存优化参数的配置,每种持久化方式的利与弊以及主从复制的原理以及配置 一.常用内存优化手段与参数 redis的性能如何是完全依赖于内存的,所以我们需要知道如何来控制和节省内存. 首先最重要的一点是不要开启Redis的VM选项,即虚拟内存功能,这个本来是作为Redis存储超出物理内存数据的一种数据在内存与磁盘换入换出的一个持久化策略,但是其内存管理成本非常的高,所以要关闭VM功能,请检查你的redis.conf文件中 vm-enabled 为 no. 其次最好设置下redis.c

Redis内存淘汰机制

转自:https://my.oschina.net/andylucc/blog/741965 摘要 Redis是一款优秀的.开源的内存数据库,我在阅读Redis源码实现的过程中,时时刻刻能感受到Redis作者为更好地使用内存而费尽各种心思,例如最明显的是对于同一种数据结构在不同应用场景下提供了基于不同底层编码的实现(如压缩列表.跳跃表等).今天我们暂时放下对Redis不同数据结构的探讨,来一起看看Redis提供的另一种机制——内存淘汰机制. 探初衷 Redis内存淘汰指的是用户存储的一些键被可以