Redis common interview questions Share

1. What are the benefits of using redis there?

  1. Speed, because the data stored in memory, similar to HashMap, HashMap advantage is the time complexity of finding and operations are O (1)

  2. Support for rich data types, support string, list, set, sorted set, hash

  3. Support services, operations are atomic, so-called atomic changes to the data that is either all executed or not executed all

  4. Rich Features: can be used for caching, message, press the key to set the expiration time, will be automatically deleted after the expiration

2, redis memcached What are the advantages compared to?

  1. All values ​​are simple strings memcached, redis as its replacement, support richer data types

  2. redis speed much faster than memcached

  3. persistent data which may redis

3, redis common performance problems and solutions:

  1. Master best not to do any persistent work, such as RDB memory snapshots and log files AOF

  2. If the data is more important, a Slave open AOF backup data, policy is set to sync once per second

  3. In order to replicate the master speed and stability, Master and Slave connection is preferably the same LAN

  4. Try to avoid increase from the library a lot of pressure on the main library

  5. Not copied from the master structure using FIG., One-way linked list structure is more stable, i.e.: Master <- Slave1 <- Slave2 <- Slave3 ...

Such a structure convenient single point of failure to solve the issue and realize the replacement of Master of Slave. If the Master hung up, you can turn immediately Slave1 do Master, the other unchanged.

4, redis most appropriate scene

Redis most suitable for all data in-momory scene, although Redis also provide lasting capabilities, but is actually more of a disk-backed function, with persistence in the traditional sense has a relatively large difference, then we will probably have questions, it seems more like a Redis enhanced version of Memcached, then when to use Memcached, Redis when to use it?

If you simply compare the difference between Redis and Memcached, most will get the following view:

  1. Redis not only support simple k / v types of data, while also providing a storage list, set, zset, hash and other data structures.

  2. Redis supports backup data, i.e., data backup master-slave mode.

  3. Redis supports data persistence, data in memory can be kept on disk, restart when you can load be used again.

(1) the session cache (Session Cache) The most common scenario is using Redis session cache (session cache). Redis caching session with than other storage (such as Memcached) has the advantage of: Redis provide persistence. When not strictly required to maintain a cache coherency, if the user's shopping cart information lost, most people will be unhappy, and now, they will do so? Fortunately, with the improvement of Redis these years, it's easy to find the right document how to use Redis caching session. Even well-known business platform Magento also offers Redis plug-ins.

(2) full-page cache (FPC) in addition to the basic session token, Redis also provides a very convenient platform for FPC. Back consistency, even restart Redis instance, because of the persistent disk, users will not see a decrease page loading speed, which is a great improvement, similar to PHP local FPC. Magento again as an example, Magento offers a plug-in to use Redis as a full-page cache backend. In addition, the WordPress user, Pantheon has a great plugin wp-redis, this plugin can help you with the fastest speed of loading pages you've visited.

(4) Ranking / counter Redis of numbers increment or decrement operation to achieve very good in memory. Collection (Set) and an ordered set (Sorted Set) also allows us the time to perform these operations become very simple, Redis just provide just these two data structures. So, we need to sort the collection to get the highest ranked 10 users - what we call "user_scores", we just need to execute something like the following: Of course, this assumes you are doing based on your user's score ascending order. If you want to return the user and the user's score, you need to perform: ZRANGE user_scores 0 10 WITHSCORES Agora Games is a good example, implemented in Ruby, its ranking is to use Redis to store data, you can here see.

(5) Publish / Subscribe Last (but certainly not least) is Redis publish / subscribe functionality. Publish / Subscribe usage scenario is indeed very much. I have seen people use social networking connections, but also to build a chat system based publish / subscribe Script Triggers, and even publish Redis / subscribe functionality! (No, it's true, you can go to verify).

Redis offers all the features, I feel like this is the least of a person, although it provides users if this multifunction.

5, redis some of the other features

(1) Redis is single-threaded, single-process redis queuing technologies will become concurrent access serial access, eliminating the overhead of traditional database Serial Control

(2) by increasing the number of separate read and write model Slave DB, the read performance can be linear growth. To avoid single points of failure of the Master DB, generally using two cluster Master DB do hot standby, so the availability of the entire cluster of reading and writing are very high. Defects separate read and write architecture that whether it is Master or Slave, each node must preserve the integrity of the data, if in the case of large amount of data, scalability cluster storage capacity is limited to a single node, but also for write-intensive type of application, the architecture is not suitable for separate read and write.

(3) In order to solve the model data piece separate read and write defect model, the model may be applied data piece to come. Each node can be thought of are independent master, and implement service data piece through. The above combination of the two models, each of the master may be designed to model consists of a plurality of master and slave thereof.

(4) Redis recovery strategy

  1. volatile-lru: selection of the least recently used data out of the set of data set expiration time (server.db [i] .expires) in

  2. volatile-ttl: selection of data to be expired expiration time has been set out from the data set (server.db [i] .expires) in

  3. volatile-random: the expiration time has been set from the data set (server.db [i] .expires) arbitrarily selected out of the data

  4. allkeys-lru: selection of the least recently used data out from the data set (server.db [i] .dict) in

  5. allkeys-random: selecting out data from the data set (server.db [i] .dict) any

  6. no-enviction (expulsion): prohibits the expulsion data

Note that the six kinds of mechanisms, volatile and allkeys provides is a set expiration time of data collection or data out of the data from the entire data set out of the back of the lru, ttl and random three different phase-out strategy, coupled with a kind of no-enviction never recovered strategy.

Use policy rules:

  1. If the data is presented power-law distribution, which is part of the data access to high-frequency, low-frequency part of the data access, use allkeys-lru

  2. If the data is rendered equal distribution, that is, all data access frequency are the same, using allkeys-random

6, mySQL there 2000w data, only the data stored in redis 20w, how to ensure that the data is hot data in redis

Knowledge: redis-memory data set size up to a certain size and they will perform data elimination strategy. redis offers six data out of a strategy see above

7, if there are 100 million Redis key, which has a key 10w begins with a fixed known prefix, if all of them to find out?

Use keys instructions may sweep out a list of the specified pattern key.

Then ask each other: If this redis is providing services to the business line, use keys that instruction will be a problem?

This time you have to answer a key characteristic redis: redis single-threaded. keys instruction causes the thread blocked for some time, online services will be stalled until the instruction is finished, the service can be restored. This time can be used scan command, scan command can extract the key non-blocking list specified pattern, but there will be some duplication of probability, on the client side deduplication can be done once, but the overall time spent directly with the ratio keys commander.

8, Redis common performance problems are what? How to solve?

  1. Master write memory snapshot, save rdbSave command scheduling function, can block the main thread of the work, when the snapshot is relatively large impact on performance is very large, it will be suspended intermittently, so Master is best not to write a memory snapshot.

  2. Master AOF persistent, if not rewrite AOF documents, the impact of this persistent way on performance is minimal, but AOF files grow, AOF file too much effect on the speed of recovery Master restart. Master best not to do any persistent work, including memory snapshots and AOF log files, especially not enable memory snapshots are persistent, if the data is more critical, open a Slave AOF backup data, sync strategy once per second.

  3. Master call BGREWRITEAOF AOF rewrite the file, when AOF rewrite will account for a large amount of CPU and memory resources, resulting in service load is too high, a brief suspension of service phenomenon.

  4. Redis replication master from performance problems, in order from the master copy speed and stability, the Slave and Master is preferably connected to the same LAN

9, Redis what data structure?

String String, Dictionary Hash, List List, a collection of Set, an ordered set of SortedSet.

If you are a senior Redis users, but also need to add several data structures HyperLogLog below, Geo, Pub / Sub.

If you say also played Redis Module, like BloomFilter, RedisSearch, Redis-ML, the interviewer was eyes began to light up.

10, used Redis distributed lock it, which is what's going on?

Setnx scramble to acquire a lock, then grabbed, and then add a lock to expire expiration prevent lock forget released.

This time the other will tell you, you answer quite well, and then went on to ask if accidental crash before execution expire after setnx process or to restart maintained, then what happens?

This time you have to give feedback surprise: Well, is oh, this lock will never be released. Then you need to get yourself and scratched his head, pretending to think for a moment, as if the next result is that you take the initiative to think out, then answered: I remember a very complex instruction set of parameters, this should be possible and expire at the same time the setnx synthesis of an instruction to use! Then the other side will reveal a smile, and my heart began to recite: press, this kid is not bad.

11, used Redis what to do asynchronous queue, how do you use?

Structure is generally used as a queue list, rpush message production, lpop consumption message. Lpop when no message to a proper sleep will try again.

If the person asking it Can not sleep? There is a list of instructions called blpop, in the absence of information, it will block until the message arrives.

If the person can not produce a consumer asked many times it? Use pub / sub topic subscriber mode, you can achieve the 1: N message queue.

If they ask pub / sub What are the disadvantages? In the case of the consumer off the assembly line, production will be lost messages, message queues have to use professional as rabbitmq and so on.

If the person asking how to achieve redis delay queue? I guess now you want to put on a stick and killed the interviewer if you have got a baseball bat, then, how to ask so detailed. But you very restrained and calm demeanor replied: Use sortedset, take a timestamp as score, the message content as key to call zadd to produce news, consumer access to polling data N seconds before treated with zrangebyscore instruction.

Here, the interviewer has secretly you a thumbs-up. But he did not know at the moment is that you have put up a middle finger, the back of the chair.

12, if a large number of key needs to be set at the same time has expired, the general needs attention?

If a large number of key expiration time set too concentrated, at that point in time expired, redis may momentarily Caton phenomenon. Generally need to add a random value over time, the expiration time such that some of the dispersion.

13. Why Redis need to put all the data into memory?

Redis To achieve the fastest read and write speed data into memory, and by asynchronously writing data to disk. Therefore, fast and redis data persistence features. If you do not put the data in memory, disk I / O speed to seriously affect the performance of redis. In memory getting cheaper today, redis will become increasingly popular. If you set the maximum memory used, the data has been recorded can not continue to insert a new value after the number reached memory limit.

14, Redis persistence mechanism

bgsave to mirror the full amount of persistence, aof do incremental persistence. Because bgsave will take a long time, not real time, when a lot of downtime can result in loss of data, so it is necessary to use with aof. When redis instance restart, use bgsave persistent file to reconstruct the memory, and then use aof replay with recent operating instructions to cause a state of complete recovery before restarting.

The other asked that if a sudden power failure the machine will happen? Depending on the configuration aof log sync attributes, if performance is not required, at the time of each disk write instruction sync it, they will not lose data. But in the high performance requirements of every sync it is not realistic, generally using a timed sync, such as 1s1 times, this time it will lose most of the data 1s.

The other asked what bgsave is the principle? You are given two words on it, fork and cow. fork means redis to bgsave by creating child processes, cow means that the copy is created on write, the child, the parent and child share the data segment, the parent process continues to provide literacy services to write dirty page data will gradually and sub-process separation off.

15, Redis provides what kinds of persistent way?

  1. RDB persistent manner can be spaced able to store a snapshot of your data at a specified time.

  2. AOF persistent recorded each write operation to the server when the server restart will re-execute these commands to restore the original data, AOF command to save an additional protocol redis each write operation to the end of the file. Redis also on the AOF files for background rewritten, so that the volume will not AOF file is too large.

  3. If you just want your data exists at the time the server is running, you can not use any persistent way.

  4. You can also open two kinds of persistence simultaneously, in this case, when redis restart priority load AOF file to restore the original data, as stored under normal circumstances AOF file data set than the RDB file is saved to complete dataset.

  5. The most important thing is to understand the RDB and AOF persistence of different ways, let us RDB persistent way to start.

16, how to choose the right way of persistence?

In general, if you want to achieve comparable PostgreSQL data security, you should use both persistent feature. If you are very concerned about your data, but you can still withstand the loss of data within a few minutes, then you can just use RDB persistence.

AOF many users use only persistent, but does not recommend this approach: since the timing generating RDB Snapshot (Snapshot) is very easy database backup and recovery speed RDB data set than AOF is also faster recovery, in addition to addition to this, the use of RDB also avoid bug AOF programs mentioned earlier.

17, Pipeline What are the benefits, why should the pipeline?

Multiple IO round-trip time can be reduced to one, provided that no causal correlation between the instruction execution pipeline. Redis-benchmark used for pressure measurement can be found when a peak value of QPS redis important factor is the number of batch instruction pipeline.

18, Redis synchronization mechanism to understand it?

Redis master-slave synchronization may be used, from the synchronization. The first synchronization, the master node do bgsave once, while the recording operation of the subsequent modifications to the memory buffer, after completion rdb be synchronized to the total amount of file copy node, after the completion of copying node accepts rdb image loaded into memory. After loading is complete, and then notify the master node during operation of the modified copy to the node record synchronization reproduction synchronization process is completed.

19, Redis cluster solution and implementation

Redis Sentinal focus on high availability, downtime in the master slave automatically promoted to master, continue to provide services.

Cluster redis focus on scalability, while a single redis insufficient memory, memory fragmentation using Cluster.

20, a Redis instance maximum number of keys can be stored? List, Set, Sorted Set how many elements can be stored up to them?

Theoretically Redis keys can handle up to 232, and tested in practice, stored for each instance of at least 250 million of keys. We are testing some of the larger value.

Any list, set, and the sorted set can be put 232 elements.

In other words, Redis available memory limit value in the system memory.

21, Redis persistent data caching and how to do the expansion?

  • If Redis is used as cache usage, using consistent hashing dynamic expansion volume reduction.

  • If Redis as a persistent storage is used, you must use a fixed keys-to-nodes mapping relationship, the number of nodes does not change once it is determined. Otherwise (That is Redis node dynamically changes) must be used for data re-balancing of a system at run-time, and the current Redis cluster can only do so.

Guess you like

Origin www.linuxidc.com/Linux/2019-09/160513.htm
Recommended