Redis系列2-底层数据结构

RedisDB

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 *ready_keys;           /* Blocked keys that received a PUSH */
    dict *watched_keys;         /* WATCHED keys for MULTI/EXEC CAS */
    int id;                     /* Database ID */
    long long avg_ttl;          /* Average TTL, just for stats */
    unsigned long expires_cursor; /* Cursor of the active expire cycle. */
    list *defrag_later;         /* List of key names to attempt to defrag one by one, gradually. */
} redisDb;

RedisObject

typedef struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS; /* LRU time (relative to global lru_clock) or
                            * LFU data (least significant 8 bits frequency
                            * and most significant 16 bits access time). */
    int refcount;
    void *ptr;
} robj;
  • type:4位(bit),表示对象的类型
  • encoding:4位(bit),表示对象的内部编码,Redis 可以根据不同的使用场景来为对象设置不同的编码,大大提高了 Redis 的灵活性和效率。
  • lru: 24位(bit),高16位存储一个分钟数级别的时间戳,低8位存储访问计数(lfu : 最近访问次数)
  • refcount: 记录的是该对象被引用的次数,类型为整型。refcount 的作用,主要在于对象的引用计数和内存回收。当对象的refcount>1时,称为共享对象
  • ptr: 指针指向具体的数据

对象类型 type

image

底层数据结构

字符串对象sds

Redis 使用了 SDS(Simple Dynamic String)。用于存储字符串和整型数据。
SDS的优势:

  1. SDS 在 C 字符串的基础上加入了 free 和 len 字段,获取字符串长度:SDS 是 O(1),C 字符串是 O(n)。
    buf数组的长度=free+len+1
  2. SDS 由于记录了长度,在可能造成缓冲区溢出时会自动重新分配内存,杜绝了缓冲区溢出。
  3. 可以存取二进制数据,以字符串长度len来作为结束标识
    image

跳跃表skiplist

空间换时间,将有序链表中的部分节点分层,每一层都是一个有序链表。

字典dict

字典dict又称散列表(hash),是用来存储键值对的一种数据结构。
Redis整个数据库是用字典来存储的。(K-V结构)
对Redis进行CURD操作其实就是对字典中的数据进行CURD操作。

压缩列表ziplist

整数集合intset

快速列表quicklist

流对象stream

11种encoding

在Server.h文件中对应的encoding类型,

#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  /* Encoded as zipmap */
#define OBJ_ENCODING_LINKEDLIST 4 /* No longer used: old list encoding. */
#define OBJ_ENCODING_ZIPLIST 5 /* Encoded as ziplist */
#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 ziplists */
#define OBJ_ENCODING_STREAM 10 /* Encoded as a radix tree of listpacks */

参考文献

Redis设计与实现
Redis-SDS图解:https://blog.csdn.net/qq_33361976/article/details/109014012

posted @ 2021-09-05 19:27  狻猊的主人  阅读(48)  评论(0编辑  收藏  举报