Home Database Redis Introduction to several common basic objects in redis

Introduction to several common basic objects in redis

Feb 18, 2021 am 09:29 AM
redis object

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;
Copy after login

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. */
Copy after login

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
Copy after login

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
Copy after login

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
Copy after login

五: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]
Copy after login

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 ...]
Copy after login

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
Copy after login

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 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 configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

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.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles