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

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

Aug 19, 2020 pm 01:24 PM
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 命令的妙用,请于清空旧值的同时设置一个新值,配合原子计数器使用
Copy after login

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.

         
存储、读取、修改用户属性
Copy after login

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.消息队列
Copy after login
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 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 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)

Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 Solution to 0x80242008 error when installing Windows 11 10.0.22000.100 May 08, 2024 pm 03:50 PM

1. Start the [Start] menu, enter [cmd], right-click [Command Prompt], and select Run as [Administrator]. 2. Enter the following commands in sequence (copy and paste carefully): SCconfigwuauservstart=auto, press Enter SCconfigbitsstart=auto, press Enter SCconfigcryptsvcstart=auto, press Enter SCconfigtrustedinstallerstart=auto, press Enter SCconfigwuauservtype=share, press Enter netstopwuauserv , press enter netstopcryptS

Analyze PHP function bottlenecks and improve execution efficiency Analyze PHP function bottlenecks and improve execution efficiency Apr 23, 2024 pm 03:42 PM

PHP function bottlenecks lead to low performance, which can be solved through the following steps: locate the bottleneck function and use performance analysis tools. Caching results to reduce recalculations. Process tasks in parallel to improve execution efficiency. Optimize string concatenation, use built-in functions instead. Use built-in functions instead of custom functions.

Golang API caching strategy and optimization Golang API caching strategy and optimization May 07, 2024 pm 02:12 PM

The caching strategy in GolangAPI can improve performance and reduce server load. Commonly used strategies are: LRU, LFU, FIFO and TTL. Optimization techniques include selecting appropriate cache storage, hierarchical caching, invalidation management, and monitoring and tuning. In the practical case, the LRU cache is used to optimize the API for obtaining user information from the database. The data can be quickly retrieved from the cache. Otherwise, the cache can be updated after obtaining it from the database.

Caching mechanism and application practice in PHP development Caching mechanism and application practice in PHP development May 09, 2024 pm 01:30 PM

In PHP development, the caching mechanism improves performance by temporarily storing frequently accessed data in memory or disk, thereby reducing the number of database accesses. Cache types mainly include memory, file and database cache. Caching can be implemented in PHP using built-in functions or third-party libraries, such as cache_get() and Memcache. Common practical applications include caching database query results to optimize query performance and caching page output to speed up rendering. The caching mechanism effectively improves website response speed, enhances user experience and reduces server load.

How to use Redis cache in PHP array pagination? How to use Redis cache in PHP array pagination? May 01, 2024 am 10:48 AM

Using Redis cache can greatly optimize the performance of PHP array paging. This can be achieved through the following steps: Install the Redis client. Connect to the Redis server. Create cache data and store each page of data into a Redis hash with the key "page:{page_number}". Get data from cache and avoid expensive operations on large arrays.

How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 How to upgrade Win11 English 21996 to Simplified Chinese 22000_How to upgrade Win11 English 21996 to Simplified Chinese 22000 May 08, 2024 pm 05:10 PM

First you need to set the system language to Simplified Chinese display and restart. Of course, if you have changed the display language to Simplified Chinese before, you can just skip this step. Next, start operating the registry, regedit.exe, directly navigate to HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlNlsLanguage in the left navigation bar or the upper address bar, and then modify the InstallLanguage key value and Default key value to 0804 (if you want to change it to English en-us, you need First set the system display language to en-us, restart the system and then change everything to 0409) You must restart the system at this point.

Can navicat connect to redis? Can navicat connect to redis? Apr 23, 2024 pm 05:12 PM

Yes, Navicat can connect to Redis, which allows users to manage keys, view values, execute commands, monitor activity, and diagnose problems. To connect to Redis, select the "Redis" connection type in Navicat and enter the server details.

How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 How to find the update file downloaded by Win11_Share the location of the update file downloaded by Win11 May 08, 2024 am 10:34 AM

1. First, double-click the [This PC] icon on the desktop to open it. 2. Then double-click the left mouse button to enter [C drive]. System files will generally be automatically stored in C drive. 3. Then find the [windows] folder in the C drive and double-click to enter. 4. After entering the [windows] folder, find the [SoftwareDistribution] folder. 5. After entering, find the [download] folder, which contains all win11 download and update files. 6. If we want to delete these files, just delete them directly in this folder.

See all articles