大家都知道redis默认是16个db,但是这些db底层的设计结构是什么样的呢?

我们来简单的看一下源码,重要的字段都有所注释

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) list一些数据结构中用到的阻塞api*/
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;

redis中的所有kv都是存放在dict中的,dict类型在redis中非常重要。

字典disc的数据结构如下

typedef struct dict {
dictType *type; //
void *privdata;
dictht ht[2]; //hashtable,每个dict都有两个这样的数据结构,主要用于hash扩容
long rehashidx; /* rehashing not in progress if rehashidx == -1 rehash的作用 防止链表无限增长*/
unsigned long iterators; /* number of iterators currently running 遍历记录的一些字段*/
} dict;

redis中当出现hash冲突的时候,我们会采用头插法(链表)的方式来解决,但是链表无限增常的话hashtable会退化,退化成一个链表,影响查询效率,这个时候我们就需要对之前的数组进行扩容,把老的数据搬到新数组上面,这个过程就是rehash

接下来咱们来看看dictType的类型

typedef struct dictType {
uint64_t (*hashFunction)(const void *key);
void *(*keyDup)(void *privdata, const void *key); //key用于数据类型的复制
void *(*valDup)(void *privdata, const void *obj); //value用于数据类型的复制
int (*keyCompare)(void *privdata, const void *key1, const void *key2); //hash冲突的时候需要在冲突的值里面一个一个的对比
void (*keyDestructor)(void *privdata, void *key);
void (*valDestructor)(void *privdata, void *obj);
} dictType;
typedef struct dictht {
dictEntry **table; //指向数组的首地址 是健值对的核心结构
unsigned long size;//数组的长度
unsigned long sizemask; //恒等于size-1
unsigned long used;
} dictht;
typedef struct  {
void *key; //指向SDS的数据结构
union { //联合体表示value类型,只会用到一个字段
void *val; //指向redis对象 redisObject
uint64_t u64;
int64_t s64;
double d;
} v;
struct dictEntry *next; //头插法解决hash冲突
} dictEntry;

接下来我们看一下内存关系的对应图

typedef struct redisObject {
unsigned type:4; //当前对象类型 list string hash set zset等
unsigned encoding:4; //redis做的底层优化(编码)
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;

最后咱们有一张总的图来表是redis的内存关系

encoding存储的优化策略

1:整型编码的处理

我们先来看一个例子

127.0.0.1:6379> set type-int 12345
OK
127.0.0.1:6379> object encoding type-int
"int"
//返回的encoding类型是int
127.0.0.1:6379> set type-int-long 12345678901234567890
OK
127.0.0.1:6379> object encoding type-int-long
"embstr"
//返回的encoding类型是embstr

我们可以发现,在都是数字的时候,如果长度小于20,就会自动转换为int类型,这是redis中专门做的处理

if (len <= 20 && string2l(s, len, &value))

在一个redisObject中,就可以直接用ptr去存储整型值,而不用重新去开辟一块sds的空间

2:redis对象字符串存储相关优化
127.0.0.1:6379> set type-str-short xxx
OK
127.0.0.1:6379> object encoding type-str-short
"embstr" 127.0.0.1:6379> set type-str-long xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-x
//字符串长度45
127.0.0.1:6379> object encoding type-str-long
"raw" 127.0.0.1:6379> set type-str-long2 xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxx-
//字符串长度44
127.0.0.1:6379> object encoding type-str-long2
"embstr"

一个redisobject是存在内存中的,cpu在完成一个io的时候,它是怎么来读数据的呢,其实cup的io中有一个缓冲行的概念,在linux系统中,一个缓冲行一般是64个字节

接下来我们看看一个redis对象大概占多大的内存空间,其实我们可以大概算出来。

typedef struct redisObject {
unsigned type:4; //4bit
unsigned encoding:4; //4bit
unsigned lru:LRU_BITS; //24bit
int refcount; //4byte
void *ptr; //8byte
} robj;

一个redis对象本身就需要占 (4bit+4bit+24bit = 4byte) + 4byte + 8byte = 16byte的大小

这样的话一个缓冲行还剩余48个byte的大小,有点浪费,

48个byte,按照sds的分配策略应该在sdshdr8那个区间中,而sdshdr8本身就需要占3个字节,sds需要兼容c语言的函数库,都会在结尾加上\0,所以sdshdr8本身是占用4个字节,所以一个缓冲行中还剩余44个字节,来存储剩余的数据,所以在redis字符串对象中,当长度小于44的时候,encoding的类型是embstr,没有新开辟一块sds空间

关注我的技术公众号,每周都有优质技术文章推送。

微信扫一扫下方二维码即可关注:

redis源码之dict的更多相关文章

  1. Redis源码阅读-Dict哈希字典

    Dict和Java中的HashMap很相似,都是数组开链法解决冲突. 但是Redis为了高性能, 有很多比较微妙的方法,例如 数组的大小总是2的倍数,初始大小是4. rehash并不是一次就执行完,而 ...

  2. redis源码学习-dict

    1.字典相关的几个结构体 dict由hash table存储key-value, hash table数组每一个元素存放dictEntry链接的链表头结点,dictEntry节点存放key-value ...

  3. [Redis源码阅读]dict字典的实现

    dict的用途 dict是一种用于保存键值对的抽象数据结构,在redis中使用非常广泛,比如数据库.哈希结构的底层. 当执行下面这个命令: > set msg "hello" ...

  4. Redis源码分析(dict)

    源码版本:redis-4.0.1 源码位置: dict.h:dictEntry.dictht.dict等数据结构定义. dict.c:创建.插入.查找等功能实现. 一.dict 简介 dict (di ...

  5. Redis 源码简洁剖析 03 - Dict Hash 基础

    Redis Hash 源码 Redis Hash 数据结构 Redis rehash 原理 为什么要 rehash? Redis dict 数据结构 Redis rehash 过程 什么时候触发 re ...

  6. Redis源码研究--字典

    计划每天花1小时学习Redis 源码.在博客上做个记录. --------6月18日----------- redis的字典dict主要涉及几个数据结构, dictEntry:具体的k-v链表结点 d ...

  7. Redis源码剖析--源码结构解析

    请持续关注我的个人博客:https://zcheng.ren 找工作那会儿,看了黄建宏老师的<Redis设计与实现>,对redis的部分实现有了一个简明的认识.在面试过程中,redis确实 ...

  8. Redis源码阅读(三)集群-连接初始化

    Redis源码阅读(三)集群-连接建立 对于并发请求很高的生产环境,单个Redis满足不了性能要求,通常都会配置Redis集群来提高服务性能.3.0之后的Redis支持了集群模式. Redis官方提供 ...

  9. 如何阅读 Redis 源码?ZZ

    原文链接 在这篇文章中, 我将向大家介绍一种我认为比较合理的 Redis 源码阅读顺序, 希望可以给对 Redis 有兴趣并打算阅读 Redis 源码的朋友带来一点帮助. 第 1 步:阅读数据结构实现 ...

随机推荐

  1. Language Guide (proto3) | proto3 语言指南(一)定义消息类型

    定义消息类型 首先让我们看一个非常简单的例子.假设您想定义一个搜索请求消息格式,其中每个搜索请求都有一个查询字符串.您感兴趣的特定结果页以及每页的结果数.下面是用于定义.proto消息类型的文件. s ...

  2. 统一资源定位符 (URL)

    统一资源标识符(uniform/universal resource identifier,URI)用于表示Internet中的资源(通常是文档).URI 主要用于两种目的,其一是命名资源,尽管此时把 ...

  3. Redis集群搭建很easy

    前言 哨兵模式虽然让读写分离更加高可用,但单台服务器由于本身的内存和CPU瓶颈,对于高并发和大数据业务的应用场景还是远远不能满足:对于这种情况,有点经验的小伙伴会毫不犹豫的想到集群,搞他好几个节点,负 ...

  4. HarmonyOS单模块编译与源码导读

    我这里以3518的开发板为例进行讲解,3516的也是通用的. 下面是之前全量编译的脚本 python build.py ipcamera_hi3518ev300 -b debug HarmonyOS最 ...

  5. C/C++函数与变量前面的标识符的作用

    ​​ 作者:良知犹存 转载授权以及围观->欢迎添加Wx:Allen-Iverson-me-LYN 缅怀逝者,向英雄致敬.愿山河无恙,国泰民安. 在用C/C++写代码的时候我们经常会使用一些标识符 ...

  6. The Preliminary Contest for ICPC Asia Nanjing 2019 A The beautiful values of the palace(树状数组+思维)

    Here is a square matrix of n * nn∗n, each lattice has its value (nn must be odd), and the center val ...

  7. 2019牛客多校 Round2

    Solved:2 Rank:136 A Eddy Walker 题意:T个场景 每个场景是一个长度为n的环 从0开始 每次要么向前走要么向后走 求恰好第一次到m点且其他点都到过的概率 每次的答案是前缀 ...

  8. codeforces626E.Simple Skewness(三分)

    Define the simple skewness of a collection of numbers to be the collection's mean minus its median. ...

  9. Codeforces Round #550 (Div. 3) D. Equalize Them All (贪心,模拟)

    题意:有一组数,可以选择某个数\(a_i\)相邻的一个数\(a_j\),然后可以让\(a_i\)加上或者减去\(|a_i-a_j|\),问最少操作多少次使得数组中所有数相同. 题解:不难发现,每次操作 ...

  10. 获取csc.exe路径

    using System.Runtime.InteropServices; var frameworkPath = RuntimeEnvironment.GetRuntimeDirectory(); ...