search
HomeDatabaseRedisRedis learning basic data structure

Redis usage tutorialThe column introduces its basic data structure

Redis learning basic data structure

Recommended (free): redis usage tutorial

Redis basic data structure

Redis has 5 basic data structures: String (string), list (list), set (set), hash (hash), zset (Ordered Collection)

String string

The string type is the simplest data structure of Redis value, similar to ArrayList (number list) in Java language, but in Redis String It is a dynamic string

String in Redis uses the method of pre-allocating redundant space

[Image upload failed...(image-724c60-1537973556456)]

set & get

>set keyname test
OK

>get keyname
test

//key如果存在就返回0
>setnx keyname test
0

>exists keyname

>del keyname
1

//批量设置
>mset key1 test1 key2 test2
OK

//批量获取
>mget key1 key2
1) test1
2) test2

key expiration

//设置5s后过期
>expire keyname 5

//setex是expire和set的复合写法
>setex keyname 5 test
OK

//5s后查询
>get keyname
NULL

count
ps: When the value is a number, you can use incr and incrby to count

>set num 10
OK

//incr默认加1
>incr num
11

//incrby后面要加上数字
>incrby num
ERR wrong number of arguments for 'incrby' command

//正确计数
>incrby num 5
16

list list

Let’s introduce another data structure of redis, list
Earlier we said that the string in redis is similar to the ArrayList in the java language, then the list in redis is similar to the LinkList (linked list). One special feature of the linked list is update And the new addition is very fast, but the index query is slow.

Why is it similar to a linklist? Because the redis list is not the same as a linklist. It is actually a form of quick list (quicklist). The list structure is as follows:

[Image upload failed. ..(image-625c1b-1537973556457)]

Here we would like to introduce the ziplist. What is the ziplist? In fact, it is a continuous memory space

As can be seen from the figure, the quick list is actually composed of a compressed list and bidirectional pointers, but we know that the linked list has two pointers, that is, prev and Next execution, this is a difference between quick list and linklist.

PS: Then when redis was designed, why was it changed to a two-way pointer? If, like a linked list, two pointers prev and next are used, traversal can also be achieved, but bidirectional pointers have an obvious advantage, that is, they occupy relatively less memory space.

Queue and stack

/* 队列:First in first out */

//加两个value
>rpush keynames key1 key2
2

//计算
>llen keynames
2

>lpop keynames
key1

>lpop keynames
key2

//rpush会自动过期的
>rpop keynames
NULL

/* 栈:First in last out */

//同样,加两个元素
>rpush keynames key1 key2
2

>rpop keynames
key2

>rpop keynames
key1

Dictionary hash

The dictionary of Redis is similar to the hashmap of the Java language. It is also an unordered two-dimensional structure, that is, the structure of an array plus a list. This is similar to redis dictionary and hashmap.

Then there are differences, such as rehash, dictionary refresh operation, hashmap is all hot hashing, when there are enough dictionaries, the performance is not very good, so redis is transformed and adopts gradual method , why is it called progressive? Because redis will not reload all, but save the old and new dictionaries, and then use scheduled tasks to move the data of the old hash to the new hash, and then recycle the hash memory space after the move.

Array of dictionary (hash) Add link structure:
[Image upload failed...(image-f5660f-1537973556457)]

>hset keynames key1 "test1"
1

>hset keynames key2 "test2"
1

//批量set
>hmset keynames key1 "test1" key2 "test2"
OK

//获取key1的值
>hget keynames key1
test1

//获取hash为keynames的长度
>hlen keynames
2

//获取全部
>hgetall keynames
1) key1
2) test1
3) key2
4) test2

Collection set

The set of redis and the hashset type in the java language are the same Kind of unordered unique .

>sadd keynames key1
1

//key1已经加过了,所以返回1
>sadd keynames key1 key2
1

>smembers keynames
1) key2
2) key1

//查询某个key是否存在,相当与contains
>sismember keynames key1
1

//相当于count
>scard keynames
2

//随意弹出key1
>spop keynames
key1

Ordered set zSet

Ordered set is more distinctive in redis. It is similar to the combination of SortedSet and HashMap. Its internal implementation is a data structure called a jump list. On the one hand, an ordered set is a set, so each element is unique. Then it can assign a score to each value, and then sort according to this score. The score is equivalent to a permission sorting identifier. ps: For this reason, ordered sets can be used to store fan information, value is the fan id, and score is the follow time

//9.0是score也就是权重
>zadd keyname 9.0 math
1

>zadd keyname 9.2 history
1

//顺序
>zrange keyname 0 -1
1) history
2) math

//逆序
>zrevrange keyname 0 -1
1) math
2) history

//相当于count()
>zcard keyname
2

获取指定key的score
>zscore keyname math
9

Jump list TODO

The above is the detailed content of Redis learning basic data structure. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:简书. If there is any infringement, please contact admin@php.cn delete
Why Use Redis? Benefits and AdvantagesWhy Use Redis? Benefits and AdvantagesApr 14, 2025 am 12:07 AM

Redis is a powerful database solution because it provides fast performance, rich data structures, high availability and scalability, persistence capabilities, and a wide range of ecosystem support. 1) Extremely fast performance: Redis's data is stored in memory and has extremely fast read and write speeds, suitable for high concurrency and low latency applications. 2) Rich data structure: supports multiple data types, such as lists, collections, etc., which are suitable for a variety of scenarios. 3) High availability and scalability: supports master-slave replication and cluster mode to achieve high availability and horizontal scalability. 4) Persistence and data security: Data persistence is achieved through RDB and AOF to ensure data integrity and reliability. 5) Wide ecosystem and community support: with a huge ecosystem and active community,

Understanding NoSQL: Key Features of RedisUnderstanding NoSQL: Key Features of RedisApr 13, 2025 am 12:17 AM

Key features of Redis include speed, flexibility and rich data structure support. 1) Speed: Redis is an in-memory database, and read and write operations are almost instantaneous, suitable for cache and session management. 2) Flexibility: Supports multiple data structures, such as strings, lists, collections, etc., which are suitable for complex data processing. 3) Data structure support: provides strings, lists, collections, hash tables, etc., which are suitable for different business needs.

Redis: Identifying Its Primary FunctionRedis: Identifying Its Primary FunctionApr 12, 2025 am 12:01 AM

The core function of Redis is a high-performance in-memory data storage and processing system. 1) High-speed data access: Redis stores data in memory and provides microsecond-level read and write speed. 2) Rich data structure: supports strings, lists, collections, etc., and adapts to a variety of application scenarios. 3) Persistence: Persist data to disk through RDB and AOF. 4) Publish subscription: Can be used in message queues or real-time communication systems.

Redis: A Guide to Popular Data StructuresRedis: A Guide to Popular Data StructuresApr 11, 2025 am 12:04 AM

Redis supports a variety of data structures, including: 1. String, suitable for storing single-value data; 2. List, suitable for queues and stacks; 3. Set, used for storing non-duplicate data; 4. Ordered Set, suitable for ranking lists and priority queues; 5. Hash table, suitable for storing object or structured data.

How to implement redis counterHow to implement redis counterApr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to use the redis command lineHow to use the redis command lineApr 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 build the redis cluster modeHow to build the redis cluster modeApr 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 read redis queueHow to read redis queueApr 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.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool