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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

See all articles