Home Database Mysql Tutorial Redis源码分析(八)---t_hash哈希转换

Redis源码分析(八)---t_hash哈希转换

Jun 07, 2016 pm 04:04 PM
hash redis analyze Hash Source code Convert

在上次的zipmap分析完之后,其实关于redis源代码结构体部分的内容其实已经全部结束了,因为下面还有几个和结构体相关的操作类,就页把他们归并到struct包下了。这类的文件有:t_hash.c,z_list,z_set.c,t_string.c,t_zset.c,这些文件的功能其实都差不多,就是

在上次的zipmap分析完之后,其实关于redis源代码结构体部分的内容其实已经全部结束了,因为下面还有几个和结构体相关的操作类,就页把他们归并到struct包下了。这类的文件有:t_hash.c,z_list,z_set.c,t_string.c,t_zset.c,这些文件的功能其实都差不多,就是用来实现Client和Server之间的命令处理的操作类,通过robj的形式,把dict,ziplist等存入robj中,进行各个转换,实现命令操作。避开了结构体原先的复杂结构,相当于是封装了结构体的操作类,今天我所讲的是t_hash,是dict哈希字典,ziplist压缩列表与robj之间的转换。统称hashType类型。由于此文件无头文件,只有.c文件,所以为了方便学习,我把方法拉了出来。

/* 下面是方法的归类 */
void hashTypeTryConversion(robj *o, robj **argv, int start, int end) /* 当hashType为ziplist时,判断对象长度是否超出了服务端可接受的ziplist最大长度,超过则转成哈希字典类型*/
void hashTypeTryObjectEncoding(robj *subject, robj **o1, robj **o2) /* 当robj用的是字典的编码方式的时候,则经过编码转换 */
int hashTypeGetFromZiplist(robj *o, robj *field,unsigned char **vstr,unsigned int *vlen,long long *vll) /* 获取ziplist压缩列表中的某个索引位置上的值 */
int hashTypeGetFromHashTable(robj *o, robj *field, robj **value) /* 获取哈希字典中的某个值 */
robj *hashTypeGetObject(robj *o, robj *field) /* 获取某个key对应的对象类型 */
int hashTypeExists(robj *o, robj *field)   /* hastType类型判断某个键是否存在 */
int hashTypeSet(robj *o, robj *field, robj *value) /* hashType设置操作,分2种情况,ziplist,和字典hashtable */
int hashTypeDelete(robj *o, robj *field)  /* hashType删除操作,分为ziplist的删除操作,和hashtable的删除操作 */
unsigned long hashTypeLength(robj *o)   /* hashType求长度操作 */
hashTypeIterator *hashTypeInitIterator(robj *subject)  /* 获取hashType迭代器 */
void hashTypeReleaseIterator(hashTypeIterator *hi) /* 释放hashType迭代器 */
int hashTypeNext(hashTypeIterator *hi) /* 通过hashType迭代器获取下一个元素 */
void hashTypeCurrentFromZiplist(hashTypeIterator *hi, int what,unsigned char **vstr,unsigned int *vlen,long long *vll) /* 根据当前迭代器的位置,获取当前ziplist的所在位置的key位置,或value该位置上的值 */
void hashTypeCurrentFromHashTable(hashTypeIterator *hi, int what, robj **dst) /* 根据当前迭代器的位置,获取当前dict的所在位置的key位置,或value该位置上的值 */
robj *hashTypeCurrentObject(hashTypeIterator *hi, int what) /* 根据当前迭代器的位置,获取当前key对象 */
robj *hashTypeLookupWriteOrCreate(redisClient *c, robj *key) /* 根据c客户端对象,找到key是否存在,创建或实现添加操作  */
void hashTypeConvertZiplist(robj *o, int enc) /* 从ziplist压缩表到hashtable的转换 */
void hashTypeConvert(robj *o, int enc) /* 对象转换操作,例如从ziplist到dict的转换 */

hashType的相关操作命令类,其实就是对上面方法的结合调用:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/* 哈希命令类型 */

void hsetCommand(redisClient *c)  /* 客户端设置指令 */

void hsetnxCommand(redisClient *c) /* 客户端设置下一个位置指令 */

void hmsetCommand(redisClient *c) /* 客户单设置命令,如果没有key,还有后续操作 */

void hincrbyCommand(redisClient *c) /* 客户端添加value值操作 */

void hincrbyfloatCommand(redisClient *c) /* 客户端添加float类型value值操作 */

static void addHashFieldToReply(redisClient *c, robj *o, robj *field) /*  */

void hgetCommand(redisClient *c) /* 客户端获取操作,如果没找到,直接不做任何操作 */

void hmgetCommand(redisClient *c) /* 客户端获取key操作,如果为空,会返回一些了NULL值 */

void hdelCommand(redisClient *c) /* 客户端删除操作 */

void hlenCommand(redisClient *c) /* 客户端求长度命令 */

static void addHashIteratorCursorToReply(redisClient *c, hashTypeIterator *hi, int what) /* 客户端添加hashType迭代器操作 */

void genericHgetallCommand(redisClient *c, int flags) /* 客户端获取操作原始方法,可以添加flag参数 */

void hkeysCommand(redisClient *c) /* 客户端获取key值命令 */

void hvalsCommand(redisClient *c) /* 客户端获取val值命令 */

void hgetallCommand(redisClient *c) /* 客户端获取key;value 2个值都获取 */

void hexistsCommand(redisClient *c) /* 客户端判断记录是否存在操作 */

void hscanCommand(redisClient *c) /* 客户端扫描操作 */

Copy after login
robj的操作实现转换的原理很简单,rob通过里面的ptr指针,存的就是真实的ziplist或者dict哈希总类,然后后面的操作都是基于此进行的,比如说下面的方法:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

/* Get the value from a hash table encoded hash, identified by field.

 * Returns -1 when the field cannot be found. */

/* 获取哈希字典中的某个值 */

int hashTypeGetFromHashTable(robj *o, robj *field, robj **value) {

    dictEntry *de;

 

    redisAssert(o->encoding == REDIS_ENCODING_HT);

     

    //通过robj->ptr里面存的dict总类或ziplist类开始寻找

    de = dictFind(o->ptr, field);

    if (de == NULL) return -1;

    //获取其中的value值

    *value = dictGetVal(de);

    return 0;

}

Copy after login
所有关于robj的相关结构体操作都会分成为2种情况处理,ZIPLIST和HASH类型就是dict类型,而且操作ziplist类型的时候要进行转码处理,当然在进行ziplist存入robj的时候要进行编码操作,可见,设计者在考虑到命令传输的时候想得还是很周到了,也考虑了安全的问题。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

/* Add an element, discard the old if the key already exists.

 * Return 0 on insert and 1 on update.

 * This function will take care of incrementing the reference count of the

 * retained fields and value objects. */

/* hashType设置操作,分2种情况,ziplist,和字典hashtable */

int hashTypeSet(robj *o, robj *field, robj *value) {

    int update = 0;

 

    if (o->encoding == REDIS_ENCODING_ZIPLIST) {

        unsigned char *zl, *fptr, *vptr;

         

        //首先对field和value进行解码

        field = getDecodedObject(field);

        value = getDecodedObject(value);

 

        zl = o->ptr;

        fptr = ziplistIndex(zl, ZIPLIST_HEAD);

        if (fptr != NULL) {

            fptr = ziplistFind(fptr, field->ptr, sdslen(field->ptr), 1);

            if (fptr != NULL) {

                /* Grab pointer to the value (fptr points to the field) */

                vptr = ziplistNext(zl, fptr);

                redisAssert(vptr != NULL);

                update = 1;

 

                //设置的操作,其实先删除,再插入语一个新值

                /* Delete value */

                zl = ziplistDelete(zl, &vptr);

 

                /* Insert new value */

                zl = ziplistInsert(zl, vptr, value->ptr, sdslen(value->ptr));

            }

        }

 

        if (!update) {

            /* Push new field/value pair onto the tail of the ziplist */

            zl = ziplistPush(zl, field->ptr, sdslen(field->ptr), ZIPLIST_TAIL);

            zl = ziplistPush(zl, value->ptr, sdslen(value->ptr), ZIPLIST_TAIL);

        }

        o->ptr = zl;

        //用完之后,引用计数递减

        decrRefCount(field);

        decrRefCount(value);

 

        /* Check if the ziplist needs to be converted to a hash table */

        if (hashTypeLength(o) > server.hash_max_ziplist_entries)

            hashTypeConvert(o, REDIS_ENCODING_HT);

    } else if (o->encoding == REDIS_ENCODING_HT) {

        //如果是字典,直接替换

        if (dictReplace(o->ptr, field, value)) { /* Insert */

            incrRefCount(field);

        } else { /* Update */

            update = 1;

        }

        //用完之后,引用计数递减

        incrRefCount(value);

    } else {

        redisPanic("Unknown hash encoding");

    }

    return update;

}

Copy after login
在这个过程中,redis代码中还用到了一个引用计数的东西,应该是为了合理的内存释放控制,在很多地方可以看到这样的操作;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

/* Higher level function of hashTypeGet*() that always returns a Redis

 * object (either new or with refcount incremented), so that the caller

 * can retain a reference or call decrRefCount after the usage.

 *

 * The lower level function can prevent copy on write so it is

 * the preferred way of doing read operations. */

/* 获取某个key的对象 */

robj *hashTypeGetObject(robj *o, robj *field) {

    robj *value = NULL;

 

    if (o->encoding == REDIS_ENCODING_ZIPLIST) {

        unsigned char *vstr = NULL;

        unsigned int vlen = UINT_MAX;

        long long vll = LLONG_MAX;

 

        if (hashTypeGetFromZiplist(o, field, &vstr, &vlen, &vll) == 0) {

            //在ziplist中获取值

            if (vstr) {

                value = createStringObject((char*)vstr, vlen);

            } else {

                value = createStringObjectFromLongLong(vll);

            }

        }

 

    } else if (o->encoding == REDIS_ENCODING_HT) {

        robj *aux;

 

        if (hashTypeGetFromHashTable(o, field, &aux) == 0) {

            //对象被引用了,计数递增

            incrRefCount(aux);

            value = aux;

        }

    } else {

        redisPanic("Unknown hash encoding");

    }

    return value;

}

Copy after login
客户端的命令操作其实是基于一个叫redisClient的对象,这个其实也就是robj对象,命令传输时,这个robj->ptr存着,具体的数据,robj->args[]存放了各种参数,后面就是调用前面的方法了,唯一不一样的是,命令调用后要有回复和更新通知操作。,下面是一个设置的命令;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

/* hashType处理客户端的命令请求 */

void hsetCommand(redisClient *c) {

    int update;

    robj *o;

 

    if ((o = hashTypeLookupWriteOrCreate(c,c->argv[1])) == NULL) return;

    hashTypeTryConversion(o,c->argv,2,3);

    hashTypeTryObjectEncoding(o,&c->argv[2], &c->argv[3]);

    //命令的操作都是通过,客户端中的对象,和存在于里面的命令参数组成

    update = hashTypeSet(o,c->argv[2],c->argv[3]);

    //操作完添加回复

    addReply(c, update ? shared.czero : shared.cone);

    //发送通知表示命令执行完毕,预测者会触发窗口上的显示

    signalModifiedKey(c->db,c->argv[1]);

    notifyKeyspaceEvent(REDIS_NOTIFY_HASH,"hset",c->argv[1],c->db->id);

     

    //客户端命令执行成功,因为客户单此时的数据时最新的,服务端的脏数据就自然多了一个,

    server.dirty++;

}

Copy after login
其他命令与此类似,就不说了。可以看见,现在慢慢的能够略微向逻辑层的代码靠近了,后面的代码也一定非常精彩。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to use the redis command How to use the redis command Apr 10, 2025 pm 08:45 PM

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

How to use redis lock How to use redis lock Apr 10, 2025 pm 08:39 PM

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

How to read the source code of redis How to read the source code of redis Apr 10, 2025 pm 08:27 PM

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

How to solve data loss with redis How to solve data loss with redis Apr 10, 2025 pm 08:24 PM

Redis data loss causes include memory failures, power outages, human errors, and hardware failures. The solutions are: 1. Store data to disk with RDB or AOF persistence; 2. Copy to multiple servers for high availability; 3. HA with Redis Sentinel or Redis Cluster; 4. Create snapshots to back up data; 5. Implement best practices such as persistence, replication, snapshots, monitoring, and security measures.

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

See all articles