search
HomeDatabaseRedisDetailed explanation of the usage scenarios of 5 data structures in Redis

The following column Redis Tutorial will introduce you to the usage scenarios of the five data structures in Redis. This article introduces the five data types in Redis: String, Hash, and List. , Set, Sorted Set are explained, friends in need can refer to it!

Detailed explanation of the usage scenarios of 5 data structures in Redis

1. redis Data structure usage scenarios

I have read the book redisbook and am already familiar with the basic functions of redis Now, I started looking at the source code of redis last week. The current goal is to fully understand the data structure of redis. We all know that there are 5 data structures in redis, so what are the usage scenarios of each data structure?

String - String
Hash - Dictionary
List - List
Set - Set
Sorted Set - Ordered set

Below we Let’s briefly explain their respective usage scenarios:

1.String——String

String data structure is a simple key-value type. Value can not only be String, but also Numbers (when the number type can be represented by Long, the encoding is an integer, and the others are stored in sdshdr as strings). Using the Strings type, the current functions of Memcached can be fully realized and more efficient. You can also enjoy Redis's scheduled persistence (you can choose RDB mode or AOF mode), operation logs, 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 命令的妙用,请于清空旧值的同时设置一个新值,配合原子计数器使用

1.Hash - Dictionary
In Memcached, we often use some structures The personalized information is packaged into a hashmap and stored as a string value (usually in JSON format) after serialization on the client, such as the user's nickname, age, gender, points, 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 situations where concurrent operations are possible (for example, two concurrent operations need to modify points). The Hash structure of Redis allows you to modify only a certain attribute value just like updating an attribute in the database.

         
存储、读取、修改用户属性

1.List——List
List is simply a linked list (redis uses a double-ended linked list to implement List), I believe you have learned the data structure knowledge Everyone should be able to understand its structure. Using the List structure, we can easily implement functions such as the latest news ranking (such as Sina Weibo'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.

Set is a set. The concept of a set is a combination of a bunch of unique values. 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 can be very convenient to implement functions such as joint 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.微博 TimeLine
2.消息队列
1.Sorted Set——Ordered Set

Compared with Sets, Sorted Sets 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, a Sorted Set that stores the grades of the entire class has a set value It can be a classmate's student number, and score can be his or her exam score. In this way, when the data is inserted into the collection, it will be naturally sorted. In addition, Sorted Sets 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 to obtain the work tasks in the reverse order of the score. Prioritize important tasks.

1. Elements with weight, such as the user score ranking list of a game
2. A relatively complex data structure, generally not used in too many scenarios

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 the pairing A certain key value performs message publishing and message subscription. 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 function is as a real-time messaging system, such as ordinary instant chat, group chat and other functions.

1. Transactions——Transactions

Who said that NoSQL does not support transactions? Although Redis Transactions does not provide strict ACID transactions (such as a series of commands submitted for execution using EXEC, If the server goes down during execution, some commands will be executed, and the rest will not be executed), but this Transactions still provides the basic function of command packaging and execution (if there is no problem with the server, a series of commands can be guaranteed They are executed together in sequence, and 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 Transactions. During this process, if the value of the Watched is modified, the Transactions will be discovered and refused to be executed.

The above is the detailed content of Detailed explanation of the usage scenarios of 5 data structures in Redis. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
Redis: Beyond SQL - The NoSQL PerspectiveRedis: Beyond SQL - The NoSQL PerspectiveMay 08, 2025 am 12:25 AM

Redis goes beyond SQL databases because of its high performance and flexibility. 1) Redis achieves extremely fast read and write speed through memory storage. 2) It supports a variety of data structures, such as lists and collections, suitable for complex data processing. 3) Single-threaded model simplifies development, but high concurrency may become a bottleneck.

Redis: A Comparison to Traditional Database ServersRedis: A Comparison to Traditional Database ServersMay 07, 2025 am 12:09 AM

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

Redis: Introduction to a Powerful In-Memory Data StoreRedis: Introduction to a Powerful In-Memory Data StoreMay 06, 2025 am 12:08 AM

Redisisahigh-performancein-memorydatastructurestorethatexcelsinspeedandversatility.1)Itsupportsvariousdatastructureslikestrings,lists,andsets.2)Redisisanin-memorydatabasewithpersistenceoptions,ensuringfastperformanceanddatasafety.3)Itoffersatomicoper

Is Redis Primarily a Database?Is Redis Primarily a Database?May 05, 2025 am 12:07 AM

Redis is primarily a database, but it is more than just a database. 1. As a database, Redis supports persistence and is suitable for high-performance needs. 2. As a cache, Redis improves application response speed. 3. As a message broker, Redis supports publish-subscribe mode, suitable for real-time communication.

Redis: Database, Server, or Something Else?Redis: Database, Server, or Something Else?May 04, 2025 am 12:08 AM

Redisisamultifacetedtoolthatservesasadatabase,server,andmore.Itfunctionsasanin-memorydatastructurestore,supportsvariousdatastructures,andcanbeusedasacache,messagebroker,sessionstorage,andfordistributedlocking.

Redis: Unveiling Its Purpose and Key ApplicationsRedis: Unveiling Its Purpose and Key ApplicationsMay 03, 2025 am 12:11 AM

Redisisanopen-source,in-memorydatastructurestoreusedasadatabase,cache,andmessagebroker,excellinginspeedandversatility.Itiswidelyusedforcaching,real-timeanalytics,sessionmanagement,andleaderboardsduetoitssupportforvariousdatastructuresandfastdataacces

Redis: A Guide to Key-Value Data StoresRedis: A Guide to Key-Value Data StoresMay 02, 2025 am 12:10 AM

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis: Caching, Session Management, and MoreRedis: Caching, Session Management, and MoreMay 01, 2025 am 12:03 AM

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

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

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.