redis学习系列(三-4)--redis基础类型初探(集合对象)

来源:互联网 发布:淘宝hiv试纸靠谱吗 编辑:程序博客网 时间:2024/06/06 20:03

集合对象的编码是 insert 和 hashtable


insert编码的集合对象使用整数集合作为底层实现,集合对象包含的所有元素都保存在整数集合里面

127.0.0.1:6379> sadd n 1 3 5
(integer) 3
127.0.0.1:6379> object encoding n
"intset"
127.0.0.1:6379> 

纯数字使用的是insert

digraph {    label = "\n 图 8-12    intset 编码的 numbers 集合对象";    rankdir = LR;    node [shape = record];    redisObject [label = " redisObject | type \n REDIS_SET | encoding \n REDIS_ENCODING_INTSET | <ptr> ptr | ... "];    intset [label = " <head> intset | encoding \n INTSET_ENC_INT16 | length \n 3 | <contents> contents "];    contents [label = " { 1 | 3 | 5 } "];    redisObject:ptr -> intset:head;    intset:contents -> contents;}

如果存储的是字符串的话使用的是hastable 

127.0.0.1:6379> sadd nums "abc" "cde" "df"
(integer) 3
127.0.0.1:6379> object encoding nums
"hashtable"
127.0.0.1:6379> 

digraph {    label = "\n 图 8-13    hashtable 编码的 fruits 集合对象";    rankdir = LR;    node [shape = record];    redisObject [label = " redisObject | type \n REDIS_SET | encoding \n REDIS_ENCODING_HT | <ptr> ptr | ... "];    dict [label = " <head> dict | <cherry> StringObject \n \"cherry\" | <apple> StringObject \n \"apple\" | <banana> StringObject \n \"banana\" ", width = 1.5];    redisObject:ptr -> dict:head;    node [shape = plaintext, label = "NULL"];    dict:apple -> nullX;    dict:banana -> nullY;    dict:cherry -> nullZ;}

编码换换

insert使用条件:

1.集合对象保存的元素都是整数值

2.集合对象保存的元素数量不超过512个

不满足的使用hashtable编码

可以通过修改 配置文件中的 set-max-intset-entries 来修改上限值


应该可以猜到,如果一开始是整数集合,如果中间改变了,插入了一个字符串,那么它的编码肯定会变

127.0.0.1:6379> object encoding n
"intset"
127.0.0.1:6379> sadd n "sss"
(integer) 1
127.0.0.1:6379> object encoding n
"hashtable"
127.0.0.1:6379> 

命令实现

因为集合键的值为集合对象, 所以用于集合键的所有命令都是针对集合对象来构建的, 表 8-10 列出了其中一部分集合键命令, 以及这些命令在不同编码的集合对象下的实现方法。


表 8-10 集合命令的实现方法

命令intset 编码的实现方法hashtable 编码的实现方法SADD调用 intsetAdd 函数, 将所有新元素添加到整数集合里面。调用 dictAdd , 以新元素为键, NULL 为值, 将键值对添加到字典里面。SCARD调用 intsetLen 函数, 返回整数集合所包含的元素数量, 这个数量就是集合对象所包含的元素数量。调用 dictSize 函数, 返回字典所包含的键值对数量, 这个数量就是集合对象所包含的元素数量。SISMEMBER调用 intsetFind 函数, 在整数集合中查找给定的元素, 如果找到了说明元素存在于集合, 没找到则说明元素不存在于集合。调用 dictFind 函数, 在字典的键中查找给定的元素, 如果找到了说明元素存在于集合, 没找到则说明元素不存在于集合。SMEMBERS遍历整个整数集合, 使用 intsetGet 函数返回集合元素。遍历整个字典, 使用 dictGetKey 函数返回字典的键作为集合元素。SRANDMEMBER调用 intsetRandom 函数, 从整数集合中随机返回一个元素。调用 dictGetRandomKey 函数, 从字典中随机返回一个字典键。SPOP调用 intsetRandom 函数, 从整数集合中随机取出一个元素, 在将这个随机元素返回给客户端之后, 调用 intsetRemove 函数, 将随机元素从整数集合中删除掉。调用 dictGetRandomKey 函数, 从字典中随机取出一个字典键, 在将这个随机字典键的值返回给客户端之后, 调用 dictDelete 函数, 从字典中删除随机字典键所对应的键值对。SREM调用 intsetRemove 函数, 从整数集合中删除所有给定的元素。调用 dictDelete 函数, 从字典中删除所有键为给定元素的键值对。












阅读全文
0 0
原创粉丝点击