Home Database Redis One article to understand the five major data types and application scenarios of Redis

One article to understand the five major data types and application scenarios of Redis

Aug 28, 2020 pm 05:16 PM
redis

Learning knowledge points in this article Redis five major data types: string, hash, list, set, sorted_set The application scenarios of each of the five major types

Foreword

Kaka compiled a roadmap to create an interview guide, and prepared to write articles according to this roadmap. Later, I found that I was adding knowledge points that were not supplemented. I also look forward to your partners joining in to help add some information. See you in the comments section!

One article to understand the five major data types and application scenarios of Redis
Insert image description here

1. string type

1-1 Basic operations of string type data

Add/modify data:set key value

Get data:get key

Delete data:del key

Add/modify multiple data: mset key value key1 value1

Get multiple data: mget key key1

Append information to the end of the original data (add it if it does not exist): append key value

##1-2 String type increase and decrease operations

Set the value to increase the value in the specified range:

incr key defaults to increase by 1 each time | incrby key value each time a new value is addedSet the data to decrease the specified range: decr key | decrby key value is the same as adding new one

「Application scenario」

Control the primary key id of the database table, which is the database table Provides primary key generation strategies to ensure the consistency of primary keys in data tables.

1-3 string type aging operation

Set expiration time:

setex key seconds value

「Application Scenario」

Implement the time-limited voting function: for example, a WeChat account can vote once an hour Realize hot information: such as popular products in the e-commerce industry and popular news on news websites

1-4 String type application scenarios

#High-frequency visits to the homepage of Weibo big V, for the number of fans and followers , Weibo numbers need to be updated from time to time. This is high-frequency information, and we can use the string type of redis to solve it. One article to understand the five major data types and application scenarios of Redis Set user information for Big V in redis, using the user's primary key and attributes as key values. The following is an implementation case. One article to understand the five major data types and application scenarios of Redis Here we need to briefly talk about the key naming rules: table name primary key primary key value field: field value. Naming according to such rules can manage our key values ​​very well.

We can also use another way to achieve it, which is to directly follow the key with a structure. For example, One article to understand the five major data types and application scenarios of Redis The above two methods can be implemented, but the first one can be very convenient for any One value is managed, and the second is that you have to change it once every time. Depending on the business scenario, just refresh it regularly.

2. Hash type

2-1 hash type data Basic operations

#Add/modify data:hset key field value

Get data: hget key field | hgetall key

Delete data: hdel key field field1

Add / Modify multiple data: hmset key field value field1 value1

Get multiple data: hmget key field field1

Get the number of fields in the table : hlen key

Get whether a field exists in the table: hexists key field

2- 2 Extended operations for hash type data

Get all field values ​​​​in the hash table: hkeys key

Get all field values ​​in the hash table: hvals key

Set the value of the specified field and increase the value of the specified range: hincrby key field increment | hincrbyfloat key field increment

##2-3 hash business scenario shopping cart

Source of this picture Since the network is not self-made, it just simulates the shopping cart scenario

In the above picture, we can see the information in the shopping cart. Next, we use redis to implement this shopping cart. One article to understand the five major data types and application scenarios of Redis

Adding a shopping cart and getting a shopping cart are implemented here. The keys are named table name primary key primary key value

In the above picture, we will have a problem that the product information storage will be repeated in large quantities. All We also need to hash the products individually. As shown in the figure below, only the product ID is storedOne article to understand the five major data types and application scenarios of RedisThere are two setting methods, one is to set multiple fields, and the other is to store it directly as json. If the information does not change frequently, you can use jsonOne article to understand the five major data types and application scenarios of Redis to provide you with a methodOne article to understand the five major data types and application scenarios of Redishsetnx key field value. If it exists, it will not be added, if not, it will be added. This function is used to prevent overwriting and useless operations when different users add the same productOne article to understand the five major data types and application scenarios of Redis

3. List type

#Data storage requirements: store multiple data and distinguish the order of storage space for the data Required data structure: One storage space stores multiple data, and the entry sequence can be reflected through the data List type: Save multiple data, the bottom layer uses a doubly linked list storage structure to implement

3-1 Basic operations of list type data

Add/modify data: lpush key value value1 | rpush key value value1

Get data: lrange key start end | lindex key index | llen key

Delete data: rpop key | lpop key

One article to understand the five major data types and application scenarios of Redis
Insert picture description here

3-2 Extended operations for list type data

Get and remove data within the specified time: blpop key1 key2 timeout | brpop key1 key2 timeout

Write a simple case for this function , easy to understand

After the terminal command on the left is executed, it will wait for 30 seconds to return the deleted data

When the add command on the right is executed, the left side will directly return the deleted dataOne article to understand the five major data types and application scenarios of Redis

3-3 list business scenario

# Above we know the basic operations of list and execute lpop key or rpop key You can delete from the do or from the right, but now there is a scenario where the likes business is done in the circle of friends, and then the data is deleted from the middle. The case is as shown below

We first add a b c d to list5 Then remove c After checking, only a b d is leftOne article to understand the five major data types and application scenarios of Redis

4. set type

New storage requirements: store large amounts of data and provide higher efficiency for query convenience Required storage structure: able to save large amounts of data, efficient internal storage mechanism, easy to query Set type: exactly the same as hash storage structure, only stores keys, not values ​​(nil), and values ​​are not allowed to be repeated

One article to understand the five major data types and application scenarios of Redis
Insert picture here Description

4-1 Basic operations of set type data

Add/modify data:sadd key member member1

Get data:smembers key

Delete data:srem key member1

Get Total amount of collection data: scard key

Judge whether the collection contains the specified data: sismember key member

One article to understand the five major data types and application scenarios of Redis
Insert picture description here

4-2 set type data expansion operation

#Randomly obtain the specified number of data in the set: srandmember key count

Randomly obtain a certain data in the collection and remove the changed data set from the collection: spop key

4-3 Set type business scenario recommendation information

Randomly push hot information, hot news, hot-selling travel, application app recommendations, follow-up recommendations, etc.

Due to the recent Kaka Write discuz, this case is to achieve attention recommendation.

Case 1: Store corresponding users in the set according to a certain recommendation mechanism, and then randomly obtain 2 users who need to be recommended each time

One article to understand the five major data types and application scenarios of Redis
In Insert picture description here

Case 2: Store corresponding users in the set according to a certain recommendation mechanism, and then the users recommended every day based on the date cannot be repeated

One article to understand the five major data types and application scenarios of Redis
Insert picture description here

4-4 set type business scenario mining user relationship

The intersection, union, and difference of two sets

<span style="display: block; background: url(https://my-wechat.mdnice.com/point.png); height: 30px; width: 100%; background-size: 40px; background-repeat: no-repeat; background-color: #272822; margin-bottom: -7px; border-radius: 5px; background-position: 10px 10px;"></span><code class="hljs" style="overflow-x: auto; padding: 16px; color: #ddd; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; font-size: 12px; -webkit-overflow-scrolling: touch; letter-spacing: 0px; padding-top: 15px; background: #272822; border-radius: 5px;"><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">sinter</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key1</span><br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">sunion</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key1</span><br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">sdiff</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key1</span><br/></code>
Copy after login

The intersection, union, and difference of two sets are stored in the specified set

<span style="display: block; background: url(https://my-wechat.mdnice.com/point.png); height: 30px; width: 100%; background-size: 40px; background-repeat: no-repeat; background-color: #272822; margin-bottom: -7px; border-radius: 5px; background-position: 10px 10px;"></span><code class="hljs" style="overflow-x: auto; padding: 16px; color: #ddd; display: -webkit-box; font-family: Operator Mono, Consolas, Monaco, Menlo, monospace; font-size: 12px; -webkit-overflow-scrolling: touch; letter-spacing: 0px; padding-top: 15px; background: #272822; border-radius: 5px;"><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">sinterstore</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">destination</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key1</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key2</span><br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">sunionstore</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">destination</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key1</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key2</span><br/><span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">sdiffstore</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">destination</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key1</span> <span class="hljs-selector-tag" style="color: #f92672; font-weight: bold; line-height: 26px;">key2</span><br/></code>
Copy after login

One article to understand the five major data types and application scenarios of RedisCase: We need to mine a mutual friend for information. For example, the number of jointly followed friends on WeChat public accounts, QQ’s recommendation mechanism for adding new friends, and in-depth mining of users’ direct connections

Based on the above cases, we can use difference sets to realize QQ’s friends who are likely to know each other.

4-5 set type business scenario to implement the PV UV IP record of the website

PV directly uses string type incr statistics That is,

UV and IP are independent and not repeated, use set to operate.

We know above that set has a characteristic that it cannot be repeated. We can easily implement this function based on this. Then use scar key to count the quantity.

As for UV as an independent visitor, you can use local cookies to achieve it. In the same way, pass the cookie to redis for recordingOne article to understand the five major data types and application scenarios of Redis

5. The sorted_set type

does not support sorting among the previous four types. The sorted_set type we will look at below supports both the storage of big data and the sorting function

5-1. Basic operations of sorted_set type

##Add data:

zadd key score member

Get data:

zrange key start stop | zrevrange key start stop

Delete data: zrem key member

One article to understand the five major data types and application scenarios of RedisGet data based on conditions: zrangebyscore key min max limit | zrevrangescore key max min

Conditional deletion of data: zremrangebyrank key start stop | zremrangebyscore key min max

Get the total amount of collection data: zcard key | zcount key min max

Set intersection and union operations: zinterstore destination numkeys key | zunionstore destination numkeys key(This command will not be demonstrated, you can check the document yourself. It is similar to set, except that the sum of all intersections will be given Add it up. Then there is numkeys here. This parameter is a total of several keys for calculation. How many keys are needed later)

Get the index corresponding to the data: zrank key member | zrevrank key member

socre value acquisition and modification: zscore key member | zincrby key increment member

Related recommendations: "<a href="https://www.php.cn/redis/" target="_blank">redis tutorial</a>"

Summary

The above is a brief introduction and specific application of the redis data type. In the following article, we will conduct actual combat based on specific needs. .

Persistence in learning, persistence in blogging, and persistence in sharing are the beliefs that Kaka has always upheld since his career. I hope that Kaka’s articles in the huge Internet can bring you a little Silk help. See you next time.

The above is the detailed content of One article to understand the five major data types and application scenarios of 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
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 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 implement redis counter How to implement redis counter Apr 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 set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

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