分享

(七) zipmap压缩图

 太极混元天尊 2018-05-03

系列目录 

  redis源码分析序

(一)Redis结构解析

(二)结构体分析

(三)dict哈希结构1

(三)dict哈希结构2

(三)dict哈希结构3

(三)dict哈希结构4

(四)sds字符串

(五)sparkline微线图

(六)ziplist压缩列表

(七)zipmap压缩图

(八)t_hash哈希转换

(九)t_list,t_string的分析

(十)testhelp.h小型测试框架和redis-check-aof.c日志检测

(十一)memtest内存检测

(十二)redis-check-dump本地数据库检测

(十三)redis-benchmark性能测试

(十四)rdb.c本地数据库操

(十五)aof-append only file解析

(十六)config配置文件

(十七)multi事务操作

(十八)db.c内存数据库操作

(十九)replication主从数据复制的实现

(二十) ae事件驱动

(二十一)anet网络通信的封装

(二十二)networking网络协议传输

(二十三)CRC循环冗余算法和RAND随机数算法

(二十四)tool工具类

(二十五)zmalloc内存分配实现

(二十六)slowLog和hyperloglog

(二十七)rio系统I/O的封装

(二十八)object创建和释放redisObject对象

(二十九)bio后台I/O服务的实现

(三十) pubsub发布订阅模式

(三十一)latency延迟分析处理

(三十二)redis-cli.c客户端命令行接口的实现(1)

(三十三)redis-cli.c客户端命令行接口的实现(2)

(三十四)redis.h服务端的实现分析(1)

(三十五)redis.c服务端的实现分析(2)

(三十六)Redis中的优秀设计之处

如果有看过之前我分析的ziplist压缩列表的分析的话,理解这个我觉得不是什么特别的难题。ziplist压缩列表和zipmap都采用了动态分配字节的做法表示长度,比如通过固定的字节表示节省了不少的空间。同样带来的问题就是复杂的指针移动,和字符位置移动。但总的来说,一定是利大于弊了,要不然设计者也不会这么做。ziplist保存的使用一个列表,zipmap就保存的则是一个个键值对,通过key:value key:value的形式连着。下面我给出zipmap的结构构成,zipmap其实也就是一个超级长的字符串
里面涉及了几个变量zmlen,len,free,下面给出完整的解释:

1/* String -> String Map data structure optimized for size.
2 * This file implements a data structure mapping strings to other strings
3 * implementing an O(n) lookup data structure designed to be very memory
4 * efficient.
5 *
6 * The Redis Hash type uses this data structure for hashes composed of a small
7 * number of elements, to switch to a hash table once a given number of
8 * elements is reached.
9 *
10 * Given that many times Redis Hashes are used to represent objects composed
11 * of few fields, this is a very big win in terms of used memory.
12 *
13 * zipmap压缩表和ziplist十分类似,都做到了内存操作效率比较高的
14 * --------------------------------------------------------------------------
15 *
16 * Copyright (c) 2009-2010, Salvatore Sanfilippo
17 * All rights reserved.
18 *
19 * Redistribution and use in source and binary forms, with or without
20 * modification, are permitted provided that the following conditions are met:
21 *
22 *   * Redistributions of source code must retain the above copyright notice,
23 *     this list of conditions and the following disclaimer.
24 *   * Redistributions in binary form must reproduce the above copyright
25 *     notice, this list of conditions and the following disclaimer in the
26 *     documentation and/or other materials provided with the distribution.
27 *   * Neither the name of Redis nor the names of its contributors may be used
28 *     to endorse or promote products derived from this software without
29 *     specific prior written permission.
30 *
31 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
32 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
35 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
36 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
37 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
38 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
39 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
41 * POSSIBILITY OF SUCH DAMAGE.
42 */
 
1/* Memory layout of a zipmap, for the map 'foo' => 'bar', 'hello' => 'world':
2 *
3 * 'foo''bar''hello''world'
4 *
5 * is 1 byte length that holds the current size of the zipmap.
6 * When the zipmap length is greater than or equal to 254, this value
7 * is not used and the zipmap needs to be traversed to find out the length.
8 * 占有着1个字节,所以他的最多可代表的数量是254,当zipmap中的元素记录超过这个数时,
9 * 那只能从前往后后遍历算大小了,和ziplist是不一样的。
10 *
11 * is the length of the following string (key or value).
12 * lengths are encoded in a single value or in a 5 bytes value.
13 * If the first byte value (as an unsigned 8 bit value) is between 0 and
14 * 252, it's a single-byte length. If it is 253 then a four bytes unsigned
15 * integer follows (in the host byte ordering). A value of 255 is used to
16 * signal the end of the hash. The special value 254 is used to mark
17 * empty space that can be used to add new key/value pairs.
18 * 代表了后面字符串key 或 value的值的长度,长度一般被编码1个字节或5个字节表示,这个和ziplist类似
19 * 如果后面的字符串长度小于等于252个,可与用单字节表示,其他253,254等长度被用来表示其他作用了,当超过这个数时候
20 * 则直接按5字节的方式存储长度。
21 *
22 * is the number of free unused bytes after the string, resulting
23 * from modification of values associated to a key. For instance if 'foo'
24 * is set to 'bar', and later 'foo' will be set to 'hi', it will have a
25 * free byte to use if the value will enlarge again later, or even in
26 * order to add a key/value pair if it fits.
27 * 一般来表示后面的value长度的空闲值,当key:value=“foo”:'bar',后来被改为“foo”:'hi',空闲长度就为1了
28 *
29 * is always an unsigned 8 bit number, because if after an
30 * update operation there are more than a few free bytes, the zipmap will be
31 * reallocated to make sure it is as small as possible.
32 * 的数字一般比较小,如果空闲太大,zipmap会进行调整大小使map整体变得尽可能小
33 *
34 * The most compact representation of the above two elements hash is actually:
35 * 这是一个例子:
36 * 'foo''bar''hello''world'  
37 * <总键值对数><第一个key的长度>key字符<第一个value的长度><空闲长度开始都为0>后面同前
38 * '\x02\x03foo\x03\x00bar\x05hello\x05\x00world\xff'
39 *
40 * Note that because keys and values are prefixed length 'objects',
41 * the lookup will take O(N) where N is the number of elements
42 * in the zipmap and *not* the number of bytes needed to represent the zipmap.
43 * This lowers the constant times considerably.
44 */
 

说到键值对,里面最最重要的方法当然是根据key ,setValue的方法了,方法如下:

1/* Set key to value, creating the key if it does not already exist.
2 * If 'update' is not NULL, *update is set to 1 if the key was
3 * already preset, otherwise to 0. */
 
4unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update) {  
5    unsigned int zmlen, offset;  
6    unsigned int freelen, reqlen = zipmapRequiredLength(klen,vlen);  
7    unsigned int empty, vempty;  
8    unsigned char *p;  
9
10    freelen = reqlen;  
11    if (update) *update = 0;  
12    //寻找key的位置  
13    p = zipmapLookupRaw(zm,key,klen,&zmlen);  
14    if (p == NULL) {  
15        /* Key not found: enlarge */  
16        //key的位置没有找到,调整zipmap的大小,准备添加操作  
17        zm = zipmapResize(zm, zmlen+reqlen);  
18        p = zm+zmlen-1;  
19        zmlen = zmlen+reqlen;  
20
21        /* Increase zipmap length (this is an insert) */  
22        //如果头字节还没有达到最大值,则递增  
23        if (zm[0] < ZIPMAP_BIGLEN) zm[0]++;  
24    } else {  
25        /* Key found. Is there enough space for the new value? */  
26        /* Compute the total length: */  
27        if (update) *update = 1;  
28        //key的位置以及找到,判断是否有空间插入新的值  
29        freelen = zipmapRawEntryLength(p);  
30        if (freelen < reqlen) {  
31            /* Store the offset of this key within the current zipmap, so
32             * it can be resized. Then, move the tail backwards so this
33             * pair fits at the current position. */
 
34             //如果没有空间插入新的值,则调整大小  
35            offset = p-zm;  
36            zm = zipmapResize(zm, zmlen-freelen+reqlen);  
37            p = zm+offset;  
38
39            /* The +1 in the number of bytes to be moved is caused by the
40             * end-of-zipmap byte. Note: the *original* zmlen is used. */
 
41            //移动空间以便增加新的值  
42            memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));  
43            zmlen = zmlen-freelen+reqlen;  
44            freelen = reqlen;  
45        }  
46    }  
47
48    /* We now have a suitable block where the key/value entry can
49     * be written. If there is too much free space, move the tail
50     * of the zipmap a few bytes to the front and shrink the zipmap,
51     * as we want zipmaps to be very space efficient. */
 
52    empty = freelen-reqlen;  
53    if (empty >= ZIPMAP_VALUE_MAX_FREE) {  
54        /* First, move the tail bytes to the front, then resize
55         * the zipmap to be bytes smaller. */
 
56        offset = p-zm;  
57        memmove(p+reqlen, p+freelen, zmlen-(offset+freelen+1));  
58        zmlen -= empty;  
59        zm = zipmapResize(zm, zmlen);  
60        p = zm+offset;  
61        vempty = 0;  
62    } else {  
63        vempty = empty;  
64    }  
65
66    /* Just write the key + value and we are done. */  
67    /* Key: */  
68    //定位到插入的位置,首先写入key值  
69    p += zipmapEncodeLength(p,klen);  
70    memcpy(p,key,klen);  
71    p += klen;  
72    /* Value: */  
73    //key值后面是value值,再次写入  
74    p += zipmapEncodeLength(p,vlen);  
75    *p++ = vempty;  
76    memcpy(p,val,vlen);  
77    return zm;  
78}  

map里返回长度的方法有点特别,就直接定位了就用一个字节存储长度:

1/* Return the number of entries inside a zipmap */  
2/* 返回map的长度 */  
3unsigned int zipmapLen(unsigned char *zm) {  
4    unsigned int len = 0;  
5    //如果第一个长度小于最大值,则直接返回  
6    if (zm[0] < ZIPMAP_BIGLEN) {  
7        len = zm[0];  
8    } else {  
9        //否则变量计算长度  
10        unsigned char *p = zipmapRewind(zm);  
11        while((p = zipmapNext(p,NULL,NULL,NULL,NULL)) != NULL) len++;  
12
13        /* Re-store length if small enough */  
14        if (len < ZIPMAP_BIGLEN) zm[0] = len;  
15    }  
16    return len;  
17}  

平常我们在redis客户端执行set key 'value'命令的时候,调用的其实就是set方法,如下:

1zm = zipmapSet(zm,(unsigned char*) 'name',4, (unsigned char*) 'foo',3,NULL);  
2zm = zipmapSet(zm,(unsigned char*) 'surname',7, (unsigned char*) 'foo',3,NULL);  
3zm = zipmapSet(zm,(unsigned char*) 'age',3, (unsigned char*) 'foo',3,NULL);  

比ziplist方法简单许多了,最后给出头文件

1/* String -> String Map data structure optimized for size.
2 *
3 * See zipmap.c for more info.
4 *
5 * --------------------------------------------------------------------------
6 *
7 * Copyright (c) 2009-2010, Salvatore Sanfilippo
8 * All rights reserved.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions are met:
12 *
13 *   * Redistributions of source code must retain the above copyright notice,
14 *     this list of conditions and the following disclaimer.
15 *   * Redistributions in binary form must reproduce the above copyright
16 *     notice, this list of conditions and the following disclaimer in the
17 *     documentation and/or other materials provided with the distribution.
18 *   * Neither the name of Redis nor the names of its contributors may be used
19 *     to endorse or promote products derived from this software without
20 *     specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
23 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
26 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
33 */
 
1#ifndef _ZIPMAP_H  
2#define _ZIPMAP_H  
3
4unsigned char *zipmapNew(void);  //创建一个新的压缩图  
5unsigned char *zipmapSet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char *val, unsigned int vlen, int *update); //设置压缩图中的某个键值对  
6unsigned char *zipmapDel(unsigned char *zm, unsigned char *key, unsigned int klen, int *deleted);  //删除压缩图上的某个键值对  
7unsigned char *zipmapRewind(unsigned char *zm);   //将在zipmapNext中被调用到  
8unsigned char *zipmapNext(unsigned char *zm, unsigned char **key, unsigned int *klen, unsigned char **value, unsigned int *vlen); //取得此键值对的下一个键值对  
9int zipmapGet(unsigned char *zm, unsigned char *key, unsigned int klen, unsigned char **value, unsigned int *vlen); //获取某个键值对  
10int zipmapExists(unsigned char *zm, unsigned char *key, unsigned int klen); //某个key值在zipmap中是否存在  
11unsigned int zipmapLen(unsigned char *zm); //zipmap压缩图的总键值对数  
12size_t zipmapBlobLen(unsigned char *zm); //压缩图的序列化到文件中所需大小  
13void zipmapRepr(unsigned char *p);  //输出的压缩图的具体信息,用于测试  
14
15#endif  

最后,基于本人对redis源代码分析有一段时间了,我把分析好的代码,同步到了我的个人github上了,放上地址大家可以一起学习:

github:https://github.com/linyiqun/Redis-Code

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多