This article brings you a summary of some questions that are often asked during interviews Redis. It simulates how the interviewer goes into depth on the topic of Redis step by step, and comprehensively examines the candidate's understanding of Redis. I hope it will be helpful to everyone.
Recommended study: "2022 latest redis interview questions and answers"
Frequently asked questions in redis interviews 12 key points
Redis is an unavoidable threshold in interviews. As long as you write that you have used Redis in your resume, you will definitely not be able to escape.
Xiao Zhang:
Hello, interviewer. I'm here for an interview.
Interviewer:
Hello, Xiao Zhang. I have read your resume and I am proficient in Redis, so I will just ask you a few Redis-related questions. First of all, my question is, is Redis single-threaded or multi-threaded?
Xiao Zhang:
The threading model used in different versions of Redis is different. Before Redis version 4.0, the single-threaded model was used, and after version 4.0, it was increased Multi-threading support.
Before 4.0, although we said that Redis was single-threaded, it only meant that its network I/O thread and Set and Get operations were completed by one thread. However, Redis persistence and cluster synchronization are still completed using other threads.
After 4.0, multi-threading support was added, mainly reflected in the asynchronous deletion function of big data, such as unlink key
, flushdb async
, flushall async
Wait
Interviewer:
The answer is very good, Then why did Redis choose to use single thread before 4.0? And is it so fast using single thread?
Xiao Zhang:
I think the main reason for choosing single thread is that it is simple to use, there is no lock competition, all operations can be completed without locks, and there are no deadlocks and threads Switching brings performance and time overhead, but at the same time, single thread cannot fully exert the performance of multi-core CPU.
As for why single thread is so fast, I think there are mainly the following reasons:
Most operations of Redis are completed in memory, and the execution efficiency in memory itself It is fast and uses efficient data structures such as hash tables and skip tables.
Using a single thread avoids multi-thread competition, saves the time and performance overhead caused by multi-thread switching, and does not cause deadlock.
The I/O multiplexing mechanism is used to handle a large number of client Socket requests, because it is based on a non-blocking I/O model, which allows Redis to efficiently communicate over the network. , the I/O read and write process is no longer blocked.
Interviewer:
Yes, How does Redis achieve no data loss?
Xiao Zhang:
Redis data is stored in the memory. In order to ensure that the Redis data is not lost, it is necessary to store the data from the memory to the disk so that it can be restarted after the server is restarted. Afterwards, the original data can be restored from the disk. This is the data persistence of Redis. There are three ways to persist Redis data.
AOF log (Append Only File, file append mode): records all operation commands and appends them to the file in the form of text.
RDB Snapshot (Redis DataBase): Write the memory data at a certain moment to the disk in binary form.
Hybrid persistence method: Redis 4.0 adds a new hybrid persistence method, integrating the advantages of RDB and AOF.
Interviewer:
Then please talk about the implementation principles of AOF and RDB respectively.
Xiao Zhang:
AOF uses post-write logging. Redis first executes the command to write the data into the memory, and then records the log to the file. The AOF log records operation commands, not actual data. If the AOF method is used for fault recovery, the entire log needs to be executed.
RDB uses a memory snapshot method. It records the data at a certain moment, not the operation. Therefore, when using the RDB method for fault recovery, you only need to directly The RDB file can be read into memory to achieve quick recovery.
Interviewer:
You just mentioned that AOF uses the "post-write log" method, while the MySQL we usually use uses the "pre-write log" method, then Why does Redis need to execute the command first and then write the data to the log?
Xiao Zhang: My forehead started to sweat. What are the questions you asked? . .
Well, this is mainly because Redis does not check the syntax of the command before writing it to the log, so it only records the successfully executed command to avoid recording the wrong command, and it is not possible to write the log after the command is executed. Will block the current write operation.
Interviewer:
What are the risks of writing a diary after ?
Xiao Zhang:
I... I don't know how to do this.
Interviewer:
Well, there are two main risks that may occur when writing logs:
Data may be lost: If Redis just After executing the command, if a failure occurs, the command may be lost.
May block other operations: AOF log is actually executed in the main thread, so when Redis writes the log file to disk, it will still block subsequent operations and cannot be executed.
I still have a question: Will RDB block threads when taking snapshots?
Xiao Zhang:
Redis provides two commands to generate RDB snapshot files, namely save and bgsave. The save command is executed in the main thread and will cause blocking. The bgsave command will create a child process for writing RDB files, avoiding blocking the main thread. This is also the default configuration of Redis RDB.
Interviewer:
RDB Can the data be modified when taking a snapshot?
Xiao Zhang:
Save is synchronous and will block client commands. It can be modified during bgsave.
Interviewer:
SoHow does Redis solve the problem of allowing data modification when bgsave takes a snapshot?
Xiao Zhang: (Why are you still asking...I™ don’t know how!)
Um, I’m not sure about this...
Interview Official:
This is mainly implemented using the sub-threads of bgsave
. The specific operations are as follows:
If the main thread performs a read operation, the main thread and bgsave
The sub-processes do not affect each other;
If the main thread performs a write operation, a copy of the modified data will be copied, and then bgsave
The sub-process will write the copy data RDB file, during this process, the main thread can still directly modify the original data.
It should be noted that the frequency of Redis execution of RDB is very important, because this will affect the integrity of snapshot data and the stability of Redis, so after Redis 4.0, an additional AOF and RDB mixed data persistence mechanism: Write the data to the file in the form of RDB, and then store the subsequent operation commands in the file in the AOF format, which not only ensures the restart speed of Redis, but also reduces the data Risk of loss.
Xiao Zhang:
I learned it.
Interviewer:
Then can you tell me how Redis achieves high availability?
Xiao Zhang:
There are three main ways to achieve high availability in Redis: master-slave replication, sentinel mode, and Redis cluster.
Master-slave replication
Synchronize data from a previous Redis server to multiple slave Redis servers, that is, a master-slave model. This is similar to MySQL The principle of master-slave replication is the same.
Sentinel Mode
When using the Redis master-slave service, there will be a problem, that is, when the Redis master-slave server appears When a failure occurs, manual recovery is required. In order to solve this problem, Redis added the sentinel mode (because the sentinel mode can monitor the master and slave servers and provide automatic disaster recovery functions).
Redis Cluster (Cluster)
Redis Cluster is a distributed and decentralized operating mode, which is based on Redis 3.0 The Redis cluster solution launched in the version distributes data on different servers to reduce the system's dependence on a single master node, thereby improving the read and write performance of the Redis service.
Interviewer:
Use the sentinel mode to ensure that there is a copy of the data, and there is a sentinel monitoring on the availability. Once the master goes down, the slave will be elected. The node is the master node, which already meets the needs of our production environment. So why do we still need to use cluster mode?
Xiao Zhang:
Well, the sentinel mode is still the master-slave mode. In the master-slave mode, we can expand the read concurrency capability by adding salve nodes, but there is no way to expand it. Writing capacity and storage capacity, storage capacity can only be the upper limit that the master node can carry. Therefore, in order to expand writing capabilities and storage capabilities, we need to introduce cluster mode.
Interviewer:
There are so many Master nodes in the cluster, how does the redis cluster determine which node to choose when storing?
Xiao Zhang:
This should be using some kind of hash algorithm, but I’m not sure. . .
Interviewer:
Okay, that’s it for today’s interview. You go back and wait for our interview notification.
Xiao Zhang:
Okay, thank you interviewer, can you tell me how redis cluster implements node selection?
Interviewer:
Redis Cluster uses a consistent hash algorithm to implement node selection. As for what a consistent hash algorithm is, you can go back and see for yourself .
Redis Cluster divides itself into 16384 Slots. Hash slots are similar to data partitions. Each key-value pair will be mapped to a hash slot according to its key. Specific execution The process is divided into two major steps.
Calculate a 16-bit value based on the key of the key-value pair according to the CRC16 algorithm.
Then use the 16bit value to modulo 16384 to get a modulus in the range of 0~16383. Each modulus represents a hash slot with a corresponding number.
Each Redis node is responsible for processing a part of the slots. If you have three master nodes ABC, the slots each node is responsible for are as follows:
This implements the selection of cluster nodes.
Recommended learning: "Redis video tutorial", "2022 latest redis interview questions and answers"
The above is the detailed content of 12 key points often asked in redis interviews (with answers). For more information, please follow other related articles on the PHP Chinese website!

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

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

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.

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

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

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


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

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version
SublimeText3 Linux latest version
