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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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: 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.

Using the Redis directive requires the following steps: Open the Redis client. Enter the command (verb key value). Provides the required parameters (varies from instruction to instruction). Press Enter to execute the command. Redis returns a response indicating the result of the operation (usually OK or -ERR).

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.

Using Redis to lock operations requires obtaining the lock through the SETNX command, and then using the EXPIRE command to set the expiration time. The specific steps are: (1) Use the SETNX command to try to set a key-value pair; (2) Use the EXPIRE command to set the expiration time for the lock; (3) Use the DEL command to delete the lock when the lock is no longer needed.

Redis uses hash tables to store data and supports data structures such as strings, lists, hash tables, collections and ordered collections. Redis persists data through snapshots (RDB) and append write-only (AOF) mechanisms. Redis uses master-slave replication to improve data availability. Redis uses a single-threaded event loop to handle connections and commands to ensure data atomicity and consistency. Redis sets the expiration time for the key and uses the lazy delete mechanism to delete the expiration key.

The best way to understand Redis source code is to go step by step: get familiar with the basics of Redis. Select a specific module or function as the starting point. Start with the entry point of the module or function and view the code line by line. View the code through the function call chain. Be familiar with the underlying data structures used by Redis. Identify the algorithm used by Redis.

Redis, as a message middleware, supports production-consumption models, can persist messages and ensure reliable delivery. Using Redis as the message middleware enables low latency, reliable and scalable messaging.
