Home > Database > Redis > body text

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

咔咔
Release: 2020-08-28 17:26:18
Original
2132 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template