


One article to understand the five major data types and application scenarios of 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!
❞

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 websites1-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. 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.
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, 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 scenarioIn the above picture, we can see the information in the shopping cart. Next, we use redis to implement this shopping cart.
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 storedThere 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 json
to provide you with a method
hsetnx 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 product
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

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 data
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 left
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

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

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

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

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>
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>
Case: 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 recording
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
zrange key start stop | zrevrange key start stop
Delete data: zrem key member
Get 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!

Redis stands out because of its high speed, versatility and rich data structure. 1) Redis supports data structures such as strings, lists, collections, hashs and ordered collections. 2) It stores data through memory and supports RDB and AOF persistence. 3) Starting from Redis 6.0, multi-threaded I/O operations have been introduced, which has improved performance in high concurrency scenarios.

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis improves application performance and scalability by caching data, implementing distributed locking and data persistence. 1) Cache data: Use Redis to cache frequently accessed data to improve data access speed. 2) Distributed lock: Use Redis to implement distributed locks to ensure the security of operation in a distributed environment. 3) Data persistence: Ensure data security through RDB and AOF mechanisms to prevent data loss.

Redis's data model and structure include five main types: 1. String: used to store text or binary data, and supports atomic operations. 2. List: Ordered elements collection, suitable for queues and stacks. 3. Set: Unordered unique elements set, supporting set operation. 4. Ordered Set (SortedSet): A unique set of elements with scores, suitable for rankings. 5. Hash table (Hash): a collection of key-value pairs, suitable for storing objects.

Redis's database methods include in-memory databases and key-value storage. 1) Redis stores data in memory, and reads and writes fast. 2) It uses key-value pairs to store data, supports complex data structures such as lists, collections, hash tables and ordered collections, suitable for caches and NoSQL databases.

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,

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.

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function