search
HomeDatabaseRedisIntroduction to usage scenarios of redis data structure

Introduction to usage scenarios of redis data structure

Mar 09, 2021 am 09:09 AM
redisscenes to be useddata structure

Introduction to usage scenarios of redis data structure

There are five data structures in the redis database, which are: string-string, Hash-dictionary, List-list, Set-set, and Sorted Set-ordered set.

These five data structures have different usage scenarios. Let’s introduce their usage scenarios below.

1. String

String data structure is a simple Key-Value type. Value can be not only String, but also a number (when the number type can be represented by Long, the encoding is an integer type. , others are stored in sdshdr as strings). Using the String type, the current functions of Memcached can be fully realized and more efficient. You can also enjoy the scheduled persistence of redis (you can choose RDB mode or AOF mode), operation log and Replication and other functions. In addition to providing the same get, set, incr, decr and other operations as Memcached, redis also provides the following operations:

1.LEN niushuai:O(1)获取字符串长度
2.APPEND niushuai redis:往字符串 append 内容,而且采用智能分配内存(每次2倍)
3.设置和获取字符串的某一段内容
4.设置及获取字符串的某一位(bit)
5.批量设置一系列字符串的内容
6.原子计数器
7.GETSET 命令的妙用,请于清空旧值的同时设置一个新值,配合原子计数器使用

2, Hash

In Memcached, we often use some The structured information is packaged into a HashMap, which is serialized on the client and stored as a string value (usually in JSON format), such as the user's nickname, age, gender, etc. At this time, when you need to modify one of the items, you usually need to take out the string (JSON), then deserialize it, modify the value of a certain item, and then serialize it into a string (JSON) and store it back. Simply modifying an attribute to do so many things must be very expensive, and it is not suitable for some situations where concurrent operations are possible (for example, two concurrent operations need to modify the age). The Hash structure of redis allows you to modify only a certain attribute value just like updating an attribute in the database. (Storing, reading, and modifying user attributes)

3. List

List is simply a linked list (redis uses a double-ended linked list to implement List). I believe that anyone who has learned data structure knowledge will Its structure should be understood. Using the List structure, we can easily implement functions such as the latest news ranking (such as Sina Blog's TimeLine). Another application of List is the message queue. You can use the Push operation of List to store tasks in the List, and then the worker thread uses the PoP operation to take out the task for execution. Redis also provides an API for operating a certain segment of elements in the List. You can directly query and delete a certain segment of elements in the List.

(Learning video sharing: redis database tutorial)

4. Set

Set is a set. The concept of a set is a bunch of unique values. The combination. Some collective data can be stored using the Set data structure provided by Redis. For example, in the Weibo application, all the followers of a user can be stored in a collection, and all the fans can be stored in a collection. Because Redis is very user-friendly and provides operations such as intersection, union, and difference for collections, it is very convenient to implement functions such as common attention, common preferences, and second-degree friends. For all the above collection operations, you can also You can use different commands to choose whether to return the results to the client or save them in a new collection.

1.共同好友、二度好友
2.利用唯一性,可以统计访问网站的所有独立 IP
3.好友推荐的时候,根据 tag 求交集,大于某个 threshold 就可以推荐

5. Sorted Set

Compared with Set, Sorted Set adds a weight parameter score to the elements in the set, so that the elements in the set can be arranged in an orderly manner according to the score. For example, in a Sorted Set that stores the grades of the entire class, the set value can be the student ID number, and the score can be the test score. In this way, when the data is inserted into the set, natural sorting has already been performed. In addition, Sorted Set can also be used to create a weighted queue. For example, the score of ordinary messages is 1 and the score of important messages is 2. Then the worker thread can choose the reverse order of the sore to obtain the work tasks. Prioritize important tasks.

2. Usage scenarios of other redis functions

1. Subscription-publishing system

Pub/Sub literally means publishing (Publish) and subscription (Subscribe). In redis, you can set up message publishing and message subscription for a certain key value. When a message is published on a key value, all clients that subscribe to it will receive the corresponding message. The most obvious use of this feature is as a real-time messaging system.

2. Transactions

Who said that NoSql does not support transactions? Although redis transactions do not provide strict ACID transactions (such as a series of commands submitted for execution using EXEC, during execution If the server is down, some commands will be executed, and the rest will not be executed), but this transaction still provides the basic function of command packaging and execution (if there is no problem with the server, it can ensure that a series of commands are in order. executed together, other client commands will be inserted in the middle for execution). Redis also provides a watch function. You can watch a key and then execute the transaction. During this process, if the value of the watch is modified, the transaction will be discovered and refused to be executed.

Related recommendations: redis database tutorial

The above is the detailed content of Introduction to usage scenarios of redis data structure. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Redis's Role: Exploring the Data Storage and Management CapabilitiesRedis's Role: Exploring the Data Storage and Management CapabilitiesApr 22, 2025 am 12:10 AM

Redis plays a key role in data storage and management, and has become the core of modern applications through its multiple data structures and persistence mechanisms. 1) Redis supports data structures such as strings, lists, collections, ordered collections and hash tables, and is suitable for cache and complex business logic. 2) Through two persistence methods, RDB and AOF, Redis ensures reliable storage and rapid recovery of data.

Redis: Understanding NoSQL ConceptsRedis: Understanding NoSQL ConceptsApr 21, 2025 am 12:04 AM

Redis is a NoSQL database suitable for efficient storage and access of large-scale data. 1.Redis is an open source memory data structure storage system that supports multiple data structures. 2. It provides extremely fast read and write speeds, suitable for caching, session management, etc. 3.Redis supports persistence and ensures data security through RDB and AOF. 4. Usage examples include basic key-value pair operations and advanced collection deduplication functions. 5. Common errors include connection problems, data type mismatch and memory overflow, so you need to pay attention to debugging. 6. Performance optimization suggestions include selecting the appropriate data structure and setting up memory elimination strategies.

Redis: Real-World Use Cases and ExamplesRedis: Real-World Use Cases and ExamplesApr 20, 2025 am 12:06 AM

The applications of Redis in the real world include: 1. As a cache system, accelerate database query, 2. To store the session data of web applications, 3. To implement real-time rankings, 4. To simplify message delivery as a message queue. Redis's versatility and high performance make it shine in these scenarios.

Redis: Exploring Its Features and FunctionalityRedis: Exploring Its Features and FunctionalityApr 19, 2025 am 12:04 AM

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.

Is Redis a SQL or NoSQL Database? The Answer ExplainedIs Redis a SQL or NoSQL Database? The Answer ExplainedApr 18, 2025 am 12:11 AM

RedisisclassifiedasaNoSQLdatabasebecauseitusesakey-valuedatamodelinsteadofthetraditionalrelationaldatabasemodel.Itoffersspeedandflexibility,makingitidealforreal-timeapplicationsandcaching,butitmaynotbesuitableforscenariosrequiringstrictdataintegrityo

Redis: Improving Application Performance and ScalabilityRedis: Improving Application Performance and ScalabilityApr 17, 2025 am 12:16 AM

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: Exploring Its Data Model and StructureRedis: Exploring Its Data Model and StructureApr 16, 2025 am 12:09 AM

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: Classifying Its Database ApproachRedis: Classifying Its Database ApproachApr 15, 2025 am 12:06 AM

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.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor