Home  >  Article  >  Database  >  Introduction to several common basic objects in redis

Introduction to several common basic objects in redis

王林
王林forward
2021-02-18 09:29:082102browse

Introduction to several common basic objects in redis

1: Preface

There are several commonly used basic objects in redis, such as string, hash, list, set, zset, etc. Let’s introduce them below The underlying implementation data structure and common application scenarios and characteristics.

2: redisobject

The source code location is located in the server.h file starting at line 605

typedef struct redisObject {
    unsigned type:4;
    unsigned encoding:4;
    unsigned lru:LRU_BITS;
    int refcount;
    void *ptr;
} robj;

2.1 type

The actual object type in redis is divided into 5 kinds of 0-4 statements. Located at line 466 in the file server.h

#define OBJ_STRING 0    /* String object. */
#define OBJ_LIST 1      /* List object. */
#define OBJ_SET 2       /* Set object. */
#define OBJ_ZSET 3      /* Sorted set object. */
#define OBJ_HASH 4      /* Hash object. */

2.2 encoding

The eight encoding formats used by redis's five objects string, list, hash, set, and zset, each encoding Corresponding to a data structure

#define OBJ_ENCODING_RAW 0    
#define OBJ_ENCODING_INT 1    
#define OBJ_ENCODING_HT 2      
#define OBJ_ENCODING_ZIPLIST 5 
#define OBJ_ENCODING_INTSET 6  
#define OBJ_ENCODING_SKIPLIST 7
#define OBJ_ENCODING_EMBSTR 8 
#define OBJ_ENCODING_QUICKLIST 9

2.3 refcount

The memory recycling in redis uses a relatively simple reference counting method. Each object reference has refcount 1. When the reference count is reduced to 0 The memory will be recycled

3: string

3.1 Common scenarios

Distributed lock: The basis for implementing distributed lock is to use the string command setnx User information: Many times User information will be serialized and stored in redis for cache, but hashing can be considered here. If only part of the user data information is used, serialization and deserialization are also an expense after all

3.2 Encoding format

int: When the string is all numbers, int encoding will be used. It is a true binary data storage embstr: the memory address is continuous and the memory is applied for once. The string length is less than 44raw: the bottom layer is implemented by sds. Compared with embstr, the difference is that the creation of sds and the creation of redisobject are implemented twice.

3.3 Common commands

# 存储
set key value

# 互斥存储
# 已存在的key再次存入数据不会更改缓存
setnx key value

# 过期存储,单位秒
# 设定key过期时间,到期自动删除
setex key seconds value

# 过期存储,单位毫秒
psetex key milliseconds value

# 批量存储
mset key value [key value ...]

# 取值
get key

# 批量取值
mget key [key ...]

# 追加
append key value

# 长度
strlen key

# 自增,只能是int编码的字符串
incr key

# 自定义步长自增
incrby key increment

# 自减,只能是int编码的字符串
# 这个可以减到负数,秒杀扣减库存啥的想想能不能用这个命令
decr key

# 自定义步长自减
decrby key increment

Four: list

4.1 Common Scenarios

Message queue: Generally not used much, after all, various MQ and Kafka are already very mature. Moreover, the message queue implemented by redis does not guarantee the security of data ranking calculation: this is only suitable for regular calculation and update, and cannot be used for real-time update of ranking. For example, Meituan calculates the list of likes for the ranking of merchants in the region every day: such as the likes in WeChat (I don’t know how to do it, guess)

4.2 Coding format

quicklist: quick list, before Versions use linkedlist and ziplist. The quicklist currently used is a combination of the two. For details, please see Redis (1) - A brief discussion of the data structure in Redis

4.3 Related parameter configuration

The configuration parameter location is located in the redis.con file Lines 1083 and 1099

list-max-ziplist-size: Configure a single ziplist size list-compress-depth: Configure the LZF compression algorithm starting node

4.4 Common commands

# 创建list并压入节点
# 压入节点位于链表头
lpush key value

# 压入节点位于链表尾
rpush key value

# 弹出list头节点
lpop key

# 弹出list尾节点
rpop key

# 删除节点
# count > 0 从左开始搜索删除count数量的value
# count < 0 从右开始搜索删除|count|数量的value
# count = 0 删除list中所有value
lrem key count value

# 范围保留
# -1 表示列表最后一个元素
# -2 表示倒数第二个,以此类推
ltrim key start stop

# 计算长度
llen key

# 索引查询节点
# index < 0 从右开始搜索
# index > 0 从左开始搜索
lindex key index

# 范围查询
# stop = -1 表示所有
lrange key start stop

# 阻塞弹出
# 队列中没有节点时会一直等待
# 多个key时表示挨着顺序依次检查,知道找到非空列表为止
# timeout可以设置等待时间,0表示一直等待
blpop key [key...] timeout
brpop key [key...] timeout

五:Hash

5.1 Common scenarios

Commodity objects and user objects. This scenario needs to be treated with verification. If the product object and user object information are required in full each time, you may wish to store string. However, if only part of the information is used, you can consider using hash structure SKU and other information. In this scenario, hash is more appropriate. A hash structure stores all skus of a certain product

5.2 Encoding format

ziplist: When using ziplist to store the hash structure, a data will use two adjacent ziplistEntry to store field and valuehashtable: When the data is stored When the parameter limit is exceeded, the underlying structure will be converted from ziplist to dict for storage

5.3 Related parameter configuration

hash-max-ziplist-entries: The default is 512, that is, the ziplist node is 1024. When the number of nodes exceeds the limit, the underlying data structure is converted to dicthash-max-ziplist-value: default 64. When any value whose length exceeds the limit is inserted into the hash, the underlying data structure is converted to dict

( Learning video sharing: redis video tutorial)

5.4 Common commands

# 存储
hset key field value 

# 不允许更改存储
# 若field值存在则本次存储不会覆盖原有value值
hsetnx key field value

# 批量存储
hmset key field value [field value ...]

# 查询
hget key field

# 批量查询
hmget key field [field ...]

# 全量查询
hgetall key 

# 全量查询field值
hkeys key

# 全量查询value值
hvals key

# 删除field
hdel key field [field ...]

# 计算键值对数量
hlen key
# field存在判断
hexists key field

# 增量式迭代
# cursor表示迭代开始的游标
# count 表示迭代返回数据数量
# pattern 表示正则匹配结果限制
hscan key cursor [Count count] [Match pattern]

6: Set

6.1 Common scenarios

Recommended: Calculate the intersection through the sinter command. For example, when Meituan recommends nearby takeout to you, it can calculate the intersection based on your takeout record and nearby merchants and push security tips: WeChat group members are saved in a set, and the user's friends are also saved in the set. When a user joins a group chat, non-friend users can be reminded to pay attention to safety

6.2 Coding format

intset: integer collection, used to store data in which all values ​​in the set collection are integers hashtable: used for field For storing set set values

6.3 Related parameter configuration

set-max-inset-entries: Default 512, which means that when the number of elements exceeds the limit, it will be converted to hashtable encoding

6.4 Commonly used commands

# 存储
sadd member [member ...]

# 弹出元素并返回
spop key count

# 查询所有元素
smembers key [count]

# 计算元素数量
scard key 

# 删除指定元素
srem key member [member ...]

# 判断元素存在
sismember key member

# 计算给定集合与后续集合差集
# 返回计算结果
sdiff key [key ...]

# 计算给定集合与后续集合差集
# 存储结果到destination并返回
sdiffstore destination key [key ...]

# 计算给定集合与后续集合交集
# 返回计算结果
sinter key [key ...]

# 计算给定集合与后续集合差集
# 存储结果到destination并返回
sinterstore destination key [key ...]

# 计算给定集合与后续集合差集
# 返回计算结果
sunion key [key ...]

# 计算给定集合与后续集合差集
# 存储结果到destination并返回
sunionstore destination key [key ...]

7: Zset

7.1 Commonly used scenarios

Ranking list: If Meituan wants to create a sales ranking list, it can use the store’s order to make the score. This query The result is an ordered weight queue: score is used as the priority, so that the weight of the data taken out is the delayed task with the highest priority execution: score is used as the task start execution time, and the value can be judged when the value is obtained.

7.2 Encoding format

ziplist: Similar to hash, both use two adjacent nodes to store score and membersskiplist: skip list structure, you can view Redis (1) -- A brief discussion of Redis Data structure

7.3 Related parameter configuration

zset-max-ziplist-entries: Default value 128, specify ziplist storage elements at most 128. If it exceeds, it will be converted to skiplistzset-max-ziplist-value: the default value is 64, and the maximum stored data value is 64 bytes. If it exceeds, it will be converted to skiplist

7.4 Common commands

# 存储
# xx 表示当zset中存在本次插入的member时才存储
# nx 表示当zset中不存在本次插入的member时才存储
zadd key [nx|xx] score member [score member ...]

# 查询排序指定[start,stop]范围内元素
# withscores 查询结果顺带返回元素分数
zrange key start stop [withscores]

# 查询指定元素分数
zscore key member

# 元素数量统计
zcard key

# 返回score位于[min,max]区间的元素数量
zcount key min max 

# 对指定元素分数增加incrment值
zincrby key incrment member

# 返回指定分数区间范围内元素
# withscores 返回时携带分数一起返回
# limit offset count表示跳过offset数量结果再返回count数量结果
zrangebyscore key min max [withscores] [limit offset count]

# 倒序返回指定分数区间范围内元素
# withscores 返回时携带分数一起返回
# limit offset count表示跳过offset数量结果再返回count数量结果
zrevrangebyscore key max min [withrescores] [limit offset count]

# 删除指定分数范围[min,max]内元素
zremrangebyscore key min max

# 移除指定元素
zrem key member

Related recommendations: redis Database tutorial

The above is the detailed content of Introduction to several common basic objects in redis. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete