RedisObject详解

[toc]

Redis中任意数据类型的键和值都会被封装成一个RedisObject,也叫作Redis对象,结构如下

1
2
3
4
5
6
7
8
// server.h
struct redisObject {
unsigned type:4; // 对象类型
unsigned encoding:4; // 编码类型
unsigned lru:LRU_BITS; // lru时间,用于内存回收
int refcount; // 引用计数器,用于判断是否可以回收
void *ptr; // 指针,指向存放实际数据的空间
};
  • 可以看出,一个Redis对象头为16字节

type:

1
2
3
4
5
6
// server.h
#define OBJ_STRING 0 /* String object. */
#define OBJ_LIST 1 /* List object. */
#define OBJ_SET 2 /* Set object. */
#define OBJ_ZSET 3 /* Sorted set object. */
#define OBJ_HASH 4 /* Hash object. */

Encoding:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// server.h
#define OBJ_ENCODING_RAW 0 /* Raw representation */
#define OBJ_ENCODING_INT 1 /* Encoded as integer */
#define OBJ_ENCODING_HT 2 /* Encoded as hash table */
#define OBJ_ENCODING_ZIPMAP 3 /* No longer used: old hash encoding. */
#define OBJ_ENCODING_LINKEDLIST 4 /* No longer used: old list encoding. */
#define OBJ_ENCODING_ZIPLIST 5 /* No longer used: old list/hash/zset encoding. */
#define OBJ_ENCODING_INTSET 6 /* Encoded as intset */
#define OBJ_ENCODING_SKIPLIST 7 /* Encoded as skiplist */
#define OBJ_ENCODING_EMBSTR 8 /* Embedded sds string encoding */
#define OBJ_ENCODING_QUICKLIST 9 /* Encoded as linked list of listpacks */
#define OBJ_ENCODING_STREAM 10 /* Encoded as a radix tree of listpacks */
#define OBJ_ENCODING_LISTPACK 11 /* Encoded as a listpack */
#define OBJ_ENCODING_LISTPACK_EX 12 /* Encoded as listpack, extended with metadata */