Resdis 40 manufacturers asked the soul, teach you how to get the interviewer

1. What is the Redis? 

Redis is completely free open source, BSD comply with the agreement, it is a high-performance key-value database. 

Redis and other key - value caching product has the following three characteristics: 

  • Redis supports data persistence, data in memory can be saved to disk, reboot to load when you can be reused.
  • Redis only supports simple key-value data types, while also providing a storage list, set, zset, hash and other data structures.
  • Redis supports backup data, i.e., data backup master-slave mode.

Redis advantage

High performance - Redis can read as fast as 110,000 times / s, write speed is 81000 times / s.
Rich data types - Redis supports binary case Strings, Lists, Hashes, Sets and
Ordered Sets data type operations.
Atomic - Redis All operations are atomic, meaning that either succeed or fail completely executed
carried out. It is a single atomic operation. A plurality of operation also supports transaction, atomicity i.e., through and EXEC MULTI
Instruction wrap.
Feature-rich - Redis also supports publish / subscribe, notification, key expiration and so on characteristics. 

Redis and other key-value store What is the difference?

Redis has a more complex data structure and provide atomic operations on them, which is a different from its
He evolutionary path of the database. Meanwhile Redis data types are based on the basic data structure of the programmer through
Ming, without the need for additional abstraction. 
When running in memory Redis but persisted to disk, so the data sets for different speed read and write
Memory tradeoff, because the data can not be greater than the amount of hardware memory. Another advantage of in-memory databases
Is compared to the same disk in the complex data structure, the operation is very simple in memory, so Redis
You can do a lot of things inside the highly complex. Meanwhile, in terms of their compact disk format to append
Way to produce because they do not require random access. 

2, Redis data types?

A: Redis supports five data types: string (string), hash (hash), list (list), set (collection) and zsetsorted set: an ordered set).
Our actual projects are more commonly used string, hash 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.

3. What are the benefits of using Redis there? 

1, fast, because the data stored in memory, similar to HashMap, HashMap advantage is the time complexity of the operation is to find and O1) 
2, support for rich data types, support string, list, set, Zset, hash, etc.
3, support services, operations are atomic, so-called atomic changes to the data that is either all executed or not executed all
4, feature-rich: can be used for caching, message, press the key to set the expiration time, will be automatically deleted after the expiration

4, Redis Memcached What are the advantages compared to? 

1, Memcached all values ​​are simple strings, redis as its replacement, the data support richer class
2, Redis is faster than Memcached
3, Redis can persist its data

5, the difference between Memcache and Redis what are? 

1, the data storage Memecache all present in the memory, will hang power failure, data can not exceed the memory size. Redis has a part on the hard disk, this will ensure persistent data. 
2, the data types supported for the data type support Memcache relatively simple. Redis complex data types. 
3, the underlying application protocol used for communication between different models of the underlying implementation therebetween and a client mode is not the same. Redis VM build their own direct mechanism, because most of the system call system function, it will waste some time to move and requests. 

6, Redis is single-threaded single-process?

A: Redis is single-threaded single-process, redis queuing technologies will become concurrent access serial access, eliminating the overhead of traditional database serial control.

7, a value of type string can store the maximum capacity is how much? 

Answer: 512M

8. What is the persistence mechanism Redis? Their advantages and disadvantages? 

Redis persistence mechanism provides two mechanisms for RDB and AOF:

1, RDBRedis DataBase) persistent way: is a snapshot of a dataset half way persistent mode) record all key-value pairs redis database, written to a temporary file data at a time point after the end of persistence, with this temporary file replaces the previous persistent file, to data recovery. 
advantage: 

1, only one file dump.rdb, convenient persistence.

2, disaster recovery is good, a file can be saved to disk security.

3, to maximize performance, fork child process to complete the write operation, so that the main process continues to process commands, so is the IO maximized. Separate subprocess to persist, the main process does not make any IO operation, to ensure the performance redis) is large with respect to the data set 4, more efficient promoter than the AOF. 
Disadvantages: 
1, data security is low. RDB is a time lag for persistence, redis If a failure occurs between persistence, data loss can occur. So this approach is more suitable for data requirements are not stringent time) 
2, AOFAppend-only file) persistent way: all the command-line recording format redis command request protocol fully persistent storage) aof saved as a file. 
advantage: 
1, data security, persistence may be configured appendfsync aof properties, there Always, once for each command to the recording operation on a file aof. 
2, by append mode write files, even if the server is down halfway, data consistency problem can be solved by redis-check-aof tool. 
3, rewrite mode AOF mechanism. Before AOF file has not been rewrite (rewrite will merge command when the file is too large), you can delete some of these commands (such as misuse of flushall))
Disadvantages:
1, AOF files larger than RDB files, and the recovery is slow.

2, the data set large, lower efficiency than the start rdb

9, Redis common performance problems and solutions: 

1, Master is best not to write a memory snapshot, if Master write memory snapshots, 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, will be intermittently suspended
2, if the data is more important, a Slave open AOF backup data, policy is set to a second synchronous

3, in order from the master copy speed and stability, Master and Slave is preferably connected in the same local area network 

4, try to avoid increased from a lot of pressure on the main library
5, not the master copy from Fig structure, the one-way linked list structure is more stable, i.e.: Master <- Slave1 <- Slave2 <- Slave3 ... solve such a configuration convenient single point of failure, the replacement of the Master Slave to achieve. If the Master hung up, you can turn immediately Slave1 do Master, the other unchanged.

10, delete the policy redis expired keys? 

1, regularly delete: key expiration time set at the same time, create a timer timer) let the timer expire at key time comes, perform the removal of the key immediately. 
2, inert Delete: faire key expires regardless, but each time get a key from the key space are made to check whether the key expires, if expired, then it deletes the key; if not expired, return the key.
3, regularly delete: from time to time program to conduct an inspection database, which deleted the expired key. As for how much you want to remove expired keys, as well as to check the number of databases, the decision by the algorithm.

11, Redis recovery strategy (phase-out strategy)?

  • volatile-lru: selection of the least recently used data out of the set of data set expiration time (server.db [i] .expires) in
  • volatile-ttl: selection of data to be expired expiration time has been set out from the data set (server.db [i] .expires) in 
  • volatile-random: the expiration time has been set from the data set (server.db [i] .expires) arbitrarily selected out of the data
  • allkeys-lru: selection of the least recently used data out from the data set (server.db [i] .dict) in
  • allkeys-random: selecting out data from the data set (server.db [i] .dict) any
  • 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 presented power-law distribution, which is part of the high data access 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

12. Why edis need to put all the data into memory?

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

13, Redis synchronization mechanism to understand it?

A: Redis can use the master-slave synchronization 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.

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

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

15, whether used Redis cluster, the cluster is what principle?

1), Redis Sentinal focus on high availability, downtime in the master slave automatically promoted to master, continue to provide services. 
2), Redis Cluster focus on scalability, single redis out of memory when using Cluster memory fragmentation. 

16, Redis clustering scheme under what circumstances would cause the entire cluster is unavailable?

A: There are clusters A, B, C three nodes, in the absence of replication model, if Node B fails, then the entire cluster will think that this lack of 5501-11000 range of slots is not available.

17, Redis supports Java client has what? Official recommended to use which? 

A: Redisson, Jedis, lettuce and so on, the official recommended Redisson. 

18, Jedis and Redisson contrast what advantages and disadvantages?

A: Jedis Redis is a Java implementation of the client, its API provides more comprehensive support for Redis commands; Redisson a distributed and scalable Java data structures, and Jedis compared to function relatively simple, does not support string operation not supported Redis characteristics ordering, transaction, plumbing, zoning and so on. Redisson aim is to promote the separation of interest to the user Redis, thereby enabling users to focus more narrowly on business logic. 

19, Redis how to set a password and verify password? 

Password: config set requirepass 123456
Authorization Password: auth 123456

20, talk about the concept of Redis hash slot? 

A: Redis cluster does not use consistent hash, but introduces the concept of hash slots, Redis hash cluster has 16,384 slots, after each key by CRC16 check of modulo 16384 to determine which slot to place, each cluster a node is responsible for a portion of hash slots. 

21, the main Redis cluster replication model from what?

A: In order to make some of the nodes fail or most nodes can not communicate the case of a cluster is still available, the
From the master to the cluster using a copy model, each node has the N-1 replicas.

22, Redis cluster will write to lose it? why?

A: Redis does not guarantee strong consistency of the data, which means that under certain conditions can in practice cluster
Write operation can be lost.

23, between Redis cluster is how to copy? 

A: asynchronous replication

24, the maximum number of cluster nodes Redis is how much?

A: 16,384.

25, Redis database cluster how to choose? 

A: Redis database cluster currently do not select the default database at 0.

26, how to test the connectivity of Redis? 

A: Use the ping command.

27, how to understand Redis affairs? 

answer:
1) A transaction is a single isolation Operation: All commands are serialized transaction performed sequentially. During execution of a transaction, the command will not be sent to other client requests interrupted. 
2) a transaction is atomic: either all commands in the transaction is executed or not executed all.

28, Redis commands related to the transaction and which of? 

答:MULTI、EXEC、DISCARD、WATCH

29, Redis key expiration time and permanent, respectively, how to set?

A: EXPIRE and PERSIST command.

30, Redis how to do memory optimization?

A: Use as a hash table (hashes), hash table (hash table is to say less inside the store number) memory used is very small, so you should be as your data model abstraction to a hash table inside. For instance, your web system has a user object, not to the user's name, last name, email, password, set up a separate key, but just think of all the information stored in the user to a hash table inside. 

31, how Redis recovery process work? 

A: A client running a new command, add new data. Redi check memory usage, if more than the limit maxmemory, the recovered according to predetermined policy. A new command is executed, and so on. So we continue through the memory limitations of the border, by constantly reach the border and then continue to recover back to the border. If the result of a command resulted in large amounts of memory to be used (for example, to save a lot of intersection of the sets to a new key), it will not be long before the memory limit is beyond the memory usage. 

32, what are ways to reduce memory usage Redis it? 

A: If you are using a 32-bit Redis instance, you can make good use of Hash, list, sorted set, set
And other types of data collection, since normally many small Key-Value can be stored in a more compact manner
Together.

33, Redis memory runs out what will happen? 

A: If you set the upper limit of reach, Redis write command returns an error message (but read command can also be positive
Chang returned. ) Or you can use Redis as cache configuration elimination mechanism, when reached Redis memory
The upper limit may wash away the old contents.

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

A: In theory Redis can handle up to 232 keys, 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. 

35, MySQL, there 2000w data, only the data stored in redis 20w, how to ensure that the data is hot data in redis? 

A: Redis memory data set size up to a certain size and they will perform data elimination strategy. 
Knowledge: Redis data available in six out of the policy:
LRU-volatile : from the most recently selected time has expiration data set (server.db [i] .expires) in
Data out of little use 
TTL-volatile : set the expiration time from a selected data set (server.db [i] .expires) to lead in the
Out period of data
Random-volatile : arbitrarily set the expiration time from the data set (server.db [i] .expires) in
Select the data out of
LRU-AllKeys : selection of the least recently used data out from the data set (server.db [i] .dict) in
Random-AllKeys : selecting out data from the data set (server.db [i] .dict) any
no-enviction (expulsion) : prohibits the expulsion data

36, Redis most appropriate scene? 

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, page caching (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.
3, queue
Reids a big advantage in the field memory storage engine is to provide a list and set operations, which makes Redis can serve as a good platform to use the message queue. Redis used as an operation queue, similar to native language (e.g., Python) push on the list / pop operations. If you do a quick search for "Redis queues" in Google, you'll be able to find a large number of open source projects, the purpose of these projects is to use Redis create a very good back-end tools to meet the needs of various queues. For example, Celery has a background is to use Redis as a broker, you can go to see from here.
4, leaderboards / counter
Redis digital up or down in memory operations are implemented very well. 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! 

37, 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? 

A: Use keys instruction may specify a mode key scan list.
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. 

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

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

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

A: Generally use the list as a queue structure, rpush production news, lpop consumer news. 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, 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, the production of news will be lost, too, such as the use of professional RabbitMQ message queue 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. 

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


to sum up:

The above summary of the 40 interview questions have readis common, often encountered in the interview, in addition to readis common interview questions, also summarized the jvm, mybatis, spring, etc. interview series topic, there is a need friends can micro-channel public No: Java programmers to gather.




Guess you like

Origin juejin.im/post/5df73f586fb9a01628013344