3

redis学习之九哈希对象

 2 years ago
source link: https://segmentfault.com/a/1190000040739910
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

redis学习之九哈希对象

发布于 9 月 26 日

之前相关联的文章:
redis学习之一SDS
redis学习之二双端链表
redis学习之三字典
redis学习之四skiplist
redis学习之五ziplist
redis学习之六对象
redis学习之七字符串对象
redis学习之八列表对象

说明:本文是基于redis2.9版本

先再看一下redisObject的定义:

typedef struct redisObject{
    //类型
    unsigned type:4;
    //编码
    unsigned encoding:4;
    //lru缓存淘汰机制信息
    unsigned lru:LRU_BITS;
    //引用计数器
    int refcount;
    //指向底层实现数据结构的指针
    void *ptr;
}robj;

哈希对象的编码可以是ziplist或hashtable。当同时满足下面两个条件时使用ziplist编码,不满足时则使用hashtable。

  1. 保存的键和值的字符串长度都小于64字节。
  2. 保存的键值对数量小于512个。

上面两个条件可以通过hash-max-ziplist-value和hash-ziplist-entries两个值进行调整。

当使用ziplist编码时有下面两个特点:

  1. 健值对作为两个节点是紧挨在一起的,健节点在前值节点紧随其后。
  2. 健节点放在ziplist表头方向,值节点放在ziplist表尾方向。

看下执行了下面命令后:

redis> HSET profile Name "Tom"
(integer) 1

redis> HSET profile Age 18
(integer) 1

存储如下图:
image.png

当使用hashtable编码时有下面两特点:

  1. hashtable里的每个键都是一个stringObject对象,对象里保存了键的内容。
  2. hashtable里的每个值都是一个stringObject对象,对象里保存了值的内容。

上面执行的命令如果使用的是hashtable,则存储如下:
image.png
(存储的格式是上面展示的,忽略里面具体的内容。。。)

参考的文章有:
黄健宏的《Redis设计与实现》一书


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK